Hibernate Study Notes ----- N-1 Association ing of Hibernate

Source: Internet
Author: User

Few things in the world we live in are isolated, and every things is bound to be associated with it. In object-oriented design, Association is very important. Associations can be divided into the following two types:
One-Way link: Only one-way access to the associated end
Bidirectional relationship: the two ends of the association can access each other.
One-way relationship can be divided into: 1-N, 1-1, N-1, N-N
Bidirectional relationship can be divided into: 1-1, 1-N, N-N
Next we will explain each of the above association mappings separately:
1. N-1 Association ing
1. Association of unidirectional N-1
1.1 N-1 Association for connectionless tables (foreign key-based N-1 Association)
For unidirectional N-1 associations, you only need to access one end of 1 from one end of N. To allow the two persistence classes to support this association ing, the program should add a new familiarity to the persistence class at one end of N. This attribute references the correlated entity at one end.
The two Association attributes are as follows (the relationship between employees and departments is used as an example ):
Employee:
[Java]
Public class Employee {
Private Integer id;
Private String name;
Private Department department; // associate attributes
 
Public Integer getId (){
Return id;
}
 
Public void setId (Integer id ){
This. id = id;
}
 
Public String getName (){
Return name;
}
 
Public void setName (String name ){
This. name = name;
}
 
Public Department getDepartment (){
Return department;
}
 
Public void setDepartment (Department department ){
This. department = department;
}
 
}
Department:
[Java]
Public class Department {
Private Integer id;
Private String name;
Private Set <Employee> employees;
 
Public Integer getId (){
Return id;
}
 
Public void setId (Integer id ){
This. id = id;
}
 
Public String getName (){
Return name;
}
 
Public void setName (String name ){
This. name = name;
}
 
Public Set <Employee> getEmployees (){
Return employees;
}
 
Public void setEmployees (Set <Employee> employees ){
This. employees = employees;
}
 
}
The Department attribute is added to the Employee end. This attribute is not a common component attribute, but a class that references another persistent class. Hibernate uses <role-to-one... /> the associated entity of the element ing N-1, directly using <transform-to-one... /> element ing to correlated entities adds a foreign key to the data table at the end of N for reference to the primary table record.
The following is a ing file for two entities:
Employee. hbm. xml
In this ing file, you must use <allow-to-one ../> to complete the association ing.
[Html] view plaincopyprint?
<Hibernate-mapping package = "com. hibernate. domain">
<Class name = "Employee" table = "employee">
<Id name = "id" column = "employeeID">
<Generator class = "native"/>
</Id>

<Property name = "name" column = "employeeName"/>
<! -- Used to map N-1 associated entities, specifying the associated entity class as: Department, specifying the foreign key as: External mentid -->
<Role-to-one class = "Department" name = "department" column = "role mentid" not-null = "true" cascade = "all"/>
</Class>
</Hibernate-mapping>
Department. hbm. xml
[Html]
<Hibernate-mapping package = "com. hibernate. domain">
<Class name = "Department" table = "department">
<Id name = "id" column = "departmentID">
<Generator class = "native"/>
</Id>

<Property name = "name" column = "departmentName"/>
</Class>
</Hibernate-mapping>
 
After the above ing, you can use the following code to save the Employee and Department entities.
[Java] view plaincopyprint?
// Add
Static void add (){
Session s = null;
Transaction tx = null;
Try {
S = HibernateUtil. getSession ();
Tx = s. beginTransaction ();

Department depart = new Department (); //... 1
Depart. setName ("Organization Department ");
 
Employee emp = new Employee ();
// Object model: establishes the relationship between two objects
Emp. setDepartment (depart); //... 2
Emp. setName ("Tang Mei Tong ");

S. save (depart); //... 3
S. save (emp); //... 4
 
Tx. commit ();
} Finally {
If (s! = Null)
S. close ();
}
}
Code Analysis:
When the code runs to... 1, a transient Department object is created. When the program runs to... 3 and... 4, the system will save the Department object and the Employee object respectively. The following two SQL statements are generated:
[SQL]
Hibernate: insert into department (departmentName) values (?)
 
E: insert into employee (employeeName, inclumentid) values (?, ?)
... 2 this statement is very important because it establishes the association between the Department and Employee objects. Without this statement, the relationship between two objects cannot be established.
Here we will switch the two statements... 3 and... 4. In this case, three SQL statements are generated. When... 3, the primary mentid is inserted as null. The system will change the primary mentid to the corresponding value only after the Department object is persisted. As follows:
[SQL]
Hibernate: insert into employee (employeeName, receivmentid) values (?, ?)
 
Hibernate: insert into department (departmentName) values (?)
 
Hibernate: update employee set employeeName = ?, Required mentid =? Where employeeID =?

If we add a non-null constraint to the foreign key in the employing file of Employee. hbm. xml, that is:
[Html]
<Role-to-one class = "Department" name = "department" column = "role mentid" not-null = "true"/>
The above code will report an empty exception: org. hibernate. PropertyValueException: not-null property references a null or transient value.
If we don't want to change the above Code, we need to be able to execute it again. That is, the slave table is persistently created. In this case, you can set cascade: cascade = "all". That is
[Html]
<Your-to-one class = "Department" name = "department" column = "Your mentid" not-null = "true" cascade = "all"/>.
By specifying cascade = "all ". This means that the system will automatically Insert the primary table records in cascade.
Therefore, in all associations based on foreign key constraints, we must keep in mind that either the corresponding entities of the primary table are always persisted first or cascade operations are set. Otherwise, if Hibernate tries to insert a slave Table Record and finds that the master table record referenced by the slave table does not exist, an exception is thrown.
 
2. N-1 association with a connection table
For the vast majority of unidirectional N-1 associations, you can use a foreign key-based association ing. However, if you need to map a unidirectional N-1 association using a join table, you need to use the <join.../> element that forces the attributes of a class to be mapped to multiple tables.
Use <join... /> when elements are mapped to the connected table, foreign key association is required. Add <key... /> the child element maps to the foreign key and is <join... /> Add <role-to-one... /> child element maps to the associated entity of the N-1. As follows:
[Html]
<Hibernate-mapping package = "com. hibernate. domain">
<Class name = "Employee" table = "employee">
<Id name = "id" column = "employeeID">
<Generator class = "native"/>
</Id>

<Property name = "name" column = "employeeName"/>
<! -- Force join table using join element -->
<Join table = "employee_department">
<! -- Reference the foreign key column of the primary key of the current table in the ing connection table -->
<Key column = "employeeID"/>
<! -- Reference the foreign key column of the joined object in the ing table -->
<Role-to-one name = "department" class = "Department" column = "external mentid"/>
</Join>
</Class>
</Hibernate-mapping>

Author: chenssy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.