First look at the User persistence class:
[Java]
Public class Users {
Private int id;
Private Date birthday;
Private Name name;
Public int getId (){
Return id;
}
Public void setId (int id ){
This. id = id;
}
Public Date getBirthday (){
Return birthday;
}
Public void setBirthday (Date birhday ){
This. birthday = birhday;
}
Public Name getName (){
Return name;
}
Public void setName (Name name ){
This. name = name;
}
}
From the User persistence class, we can see that name is no longer a simple String, but a class. Here, name is a component property. In the name class, it can contain basic data types, rule type, date type, and even components and associated entities. From the User persistence class, we cannot see whether the name is an associated object or a common component attribute. However, if we map the Name to a persistent object, the Name is the associated object. If it is not mapped to a persistence class, it is the component property. Here we do not map the Name into a persistent class.
The Name class is as follows:
[Java]
Public class Name {
Private String firstName;
Private String lastName;
Public String getFirstName (){
Return firstName;
}
Public void setFirstName (String firstName ){
This. firstName = firstName;
}
Public String getLastName (){
Return lastName;
}
Public void setLastName (String lastName ){
This. lastName = lastName;
}
}
To map the Name component in the User class, use the <component.../> element in the ing file to map the primary key element. The ing file is as follows:
User. hbm. xml
[Html]
<Hibernate-mapping package = "com. hibernate. domain">
<Class name = "Users">
<Id name = "id">
<Generator class = "native"/>
</Id>
<Property name = "birthday"/>
<! -- Map component elements -->
<Component name = "name">
<! -- The name attribute of the ing component points to the object that contains -->
<Property name = "firstName" column = "first_name"/>
<Property name = "lastName" column = "last_name"/>
</Component>
</Class>
</Hibernate-mapping>
The operation class is as follows:
[Java]
Public class UserManager {
Public static void main (String [] args ){
Session session = HibernateUtil. getSession ();
Transaction tx = session. beginTransaction ();
Users users = new Users ();
Users. setBirthday (new Date ());
Name name = new Name ();
Name. setFirstName ("first name ");
Name. setLastName ("last name ");
Users. setName (name );
Session. save (users );
Tx. commit ();
Session. close ();
}
}
Author: chenssy