[SSH advanced]-Hibernate multi-to-one ing and one-to-many ing

Source: Internet
Author: User

[SSH advanced]-Hibernate multi-to-one ing and one-to-many ing


The previous two articles talk about one-to-one ing. Here we will talk about the ing between many-to-one and one-to-many.

  

In reality, many scenarios require many-to-one or one-to-many. For example, the two class diagrams above show that a department usually has multiple employees, one employee works in only one department.

Multi-to-one association ing

In the preceding scenario, the relationship between Employee and Department is multiple to one.

PO object

Employee. java

public class Employee {    public int id;    public String name;    public Department department;    //getter、setter}

Department. java

public class Department {    public int id;    public String name;    //getter、setter}


When configuring the many-to-one relationship, when designing the po class, in addition to writing out the most basic attributes (such as the id and name of the Employee), in the class corresponding to the "many" (such as the Employee. java ).


Ing File

Employee. hbm. xml


      
               
                    
                 
     
                
                
         
     
    
   
  

Department. hbm. xml


      
               
                    
                 
     
                
        
    
   
  


The content in the ing file basically corresponds to fields in the class associated with it. The primary key is configured in The basic fields are configured in In .

Run the following table creation statement:

alter table t_employee drop foreign key FKFDCF5A196E78D697drop table if exists t_departmentdrop table if exists t_employeecreate table t_department (id integer not null auto_increment, name varchar(255), primary key (id))create table t_employee (id integer not null auto_increment, name varchar(255), departmentid integer, primary key (id))alter table t_employee add index FKFDCF5A196E78D697 (departmentid), add constraint FKFDCF5A196E78D697 foreign key (departmentid) references t_department (id)


As can be seen from the table creation statement, the foreign key of the t_employee table is associated with the primary key of the t_department table.

The generated table structure is as follows:

  


The following is a simple test.

  Insert Test

Session. beginTransaction (); Department department Department = new department (); Department. setName ("Information department"); Employee employee1 = new Employee (); employee1.setName ("Xiaohu"); employee1.setDepartment (department); Employee employee2 = new Employee (); employee2.setName ("Xiaoyu"); employee2.setDepartment (department); session. save (employee1); session. save (employee2); session. getTransaction (). commit ();


Once executed, an error is reported: org. hibernate. TransientObjectException. You can see the error at first glance, because when the department is still in the Transient status, the session cannot operate on it. Therefore, you can save the department before the transaction is committed:

Session. beginTransaction (); Department department Department = new department (); Department. setName ("Information department"); Employee employee1 = new Employee (); employee1.setName ("Xiaohu"); employee1.setDepartment (department); Employee employee2 = new Employee (); employee2.setName ("Xiaoyu"); employee2.setDepartment (department); session. save (department); session. save (employee1); session. save (employee2); session. getTransaction (). commit ();


In this way, the data can be inserted successfully:

  


Another simpler method is to map the file 'employee. hbm. xml '. ConfiguringcascadeProperty, value:"save-update":

Employee. hbm. xml


      
               
                    
                 
     
                
                
         
     
    
   
  


Cascade indicates that the operation between two objects is a linkage relationship, that is, after an operation is performed on an object, the same operation must be performed on the specified cascading object. The Hibernate document explains cascade as follows:
"Cascade (cascade) (optional): Specifies which operations will be cascading from the parent object to the associated object. Its value represents the basic Hibernate operation name, persist, merge, delete, save-update, evict, replicate, lock, refresh ...... "


  Query Test

Session. beginTransaction (); Employee employee = (Employee) session. load (Employee. class, 1); System. out. println ("name of employee:" + employee. getName (); System. out. println ("department name:" + employee. getDepartment (). getName (); session. getTransaction (). commit ();

Test results:

Employee name: Xiaoyu department name: Information department



One-to-Multiple Association ing

Since the relationship between Employee and Department is many-to-one, the opposite is that the relationship between Department and Employee is one-to-many.

Therefore, you must add a set of Employee objects to the Department PO class. This set can be a set, list, map, or even array container. Because the objects in the set cannot be duplicated and the performance is higher, set is generally used.


PO object

Department. java

public class Department {    public int id;    public String name;    public Set
  
    employees;    //getter、setter}
  

Employee. java

public class Employee {    public int id;    public String name;    //getter、setter}


Ing File

Employee. hbm. xml


      
               
                    
                 
     
                
        
    
   
  

Department. hbm. xml


      
               
                    
                 
     
                
                
                 
                   
       
      
         
    
   
  


The set tag is added to the Department. hbm. xml Department ing file. The set employees in the Department class indicates that a Department object corresponds to multiple Employee objects.


  Insert Test

Session. beginTransaction (); Employee employee1 = new Employee (); employee1.setName ("Xiaoyu"); Employee employee2 = new Employee (); employee2.setName ("Xiaoyang"); Set
  
   
Employees = new HashSet
   
    
(); Employees. add (employee1); employees. add (employee2); Department department Department = new department (); Department. setName ("Information department"); department. setEmployees (employees); session. save (employee1); session. save (employee2); session. save (department); session. getTransaction (). commit ();
   
  

Insert result:

  


  Query Test

Session. beginTransaction (); Department department Department = (Department) session. load (Department. class, 1); System. out. println ("department name:" + department. getName (); System. out. println ("department employees:"); for (employee: department. getEmployees () {System. out. print ("" + employee. getName ();} session. getTransaction (). commit ();

Console output content:

Hibernate: select department0 _. id as id0_0 _, department0 _. name as name0_0 _ from t_department department0 _ where department0 _. id =? Department name: Information department employee: Hibernate: select employees0 _. required mentid as me3_1 _, employees0 _. id as id1 _, employees0 _. id as id1_0 _, employees0 _. name as name1_0 _ from t_employee employees0 _ where employees0 _. required mentid =? Xiaoyang XiaoYu


In one-to-multiple configurations, the default value is delayed loading, which is equivalent to lazy = "true ".

In the ing File Tag attributeslazySetfalseWhen the Department is queried, all the employees belonging to the Department are queried. Console output content:

Hibernate: select department0 _. id as id0_0 _, department0 _. name as name0_0 _ from t_department department0 _ where department0 _. id =? Hibernate: select employees0 _. required mentid as me3_1 _, employees0 _. id as id1 _, employees0 _. id as id1_0 _, employees0 _. name as name1_0 _ from t_employee employees0 _ where employees0 _. required mentid =? Department name: employee of the department of the Information department: Xiaoyang XiaoYu


Comparison

Similarities: The ing principle is basically the same. When creating a table, a foreign key is added at one end of "multiple" to the other end of "one.

Difference: Different maintenance relationships
Multi-to-one maintenance relationship: when multiple links point to one, "one" can be loaded as well;
One-to-multiple maintenance relationships: one-to-many relationships can be loaded when "one" is loaded;


[Reprinted, please specify the source -- Hu Yuyang "[SSH fast advanced] -- Hibernate many-to-one ing and one-to-many ing"]
 

Related Article

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.