One-to-multiple relationship of Hibernate association relationship ing

Source: Internet
Author: User
This example shows that a unit has multiple departments, and each department has many different employees. During Storage, an employee table and a department table need to be created, stores all department and employee information, and these two tables are associated with each other by using a foreign key, so that all employees of the department can be queried Based on the department name. At the same time, all employees of the department can be queried based on the employee name.

This example shows that a unit has multiple departments, and each department has many different employees. During Storage, an employee table and a department table need to be created, stores all department and employee information, and these two tables are associated with each other by using a foreign key, so that all employees of the department can be queried Based on the department name. At the same time, all employees of the department can be queried based on the employee name.

This example shows that a unit has multiple departments, and each department has many different employees. During Storage, an employee table and a department table need to be created, stores all department and employee information, and these two tables are associated with each other by using a foreign key, so that all employees of the department can be queried Based on the department name, at the same time, the employee's department can be queried based on the employee's name.

It is not hard to see that the relationship between departments and employees is one-to-many. On the contrary, the relationship between employees and departments is one-to-one.

In POJO classes and ing files, Set sets are used to represent one-to-many objects.

The following describes some Department classes.

package entity;import java.util.HashSet;import java.util.Set;public class Department {private Integer id;private String name;private Set
 
   employees = new HashSet
  
   ();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
   
     getEmployees() {return employees;}public void setEmployees(Set
    
      employees) {this.employees = employees;}}
    
   
  
 

This class uses the Set to store employee information, indicating that there are multiple employees in a department.

Then look at the employee class.

package entity;public class Employee {private Integer id;private String name;private Department department;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;}}

This class indicates that an employee can belong to only one Department through a private Department class attribute.

Next, let's take a look at the configuration of their ing files.

First, check Department. hbm. xml.

 
     
          
               
                
            
           
               
            
           
           
           
           
           
               
                
            
       
  
 

Use The tag maps the Set attribute in the Department class. The specific attributes are explained in the annotations. Pass Indicates a one-to-many relationship between two associated classes.

Then let's look at Employee. hbm. xml.

 
     
          
               
                
            
           
               
            
           
           
           
           
       
  
 

Use Attribute specifies that the ing between the employee class and department class is many-to-one. The meaning of each element is described in the comment.

Then the ing between them has been set up. Let's take a look at the test class and use JUtil for testing.

Package test; import static org. junit. assert. *; import java. util. iterator; import java. util. set; import org. hibernate. query; import org. hibernate. session; import org. hibernate. transaction; import entity. department; import entity. employee; import factory. hibernateSessionFactory; public class Test {private Session session = null; private Transaction tran = null; // Save the object @ org. junit. testpublic void test () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {// new object Department de = new Department (); de. setId (3); de. setName ("R & D department"); Employee e1 = new Employee (); e1.setId (1); e1.setName ("Zhang San"); Employee e2 = new Employee (); e2.setId (2 ); e2.setName (""); // establishes a de ing de. getEmployees (). add (e1); de. getEmployees (). add (e2); e1.setDepartment (de); e2.setDepartment (de); // Save the data session. save (de); session. save (e1); session. save (e2); tran. commit ();} catch (Exception e) {tran. rollback () ;}// query employees by Department @ org. junit. testpublic void getDepartment () {session = HibernateSessionFactory. getSession (); String hql = "FROM Department d where d. id = 2 "; Query query = session. createQuery (hql); Department de = (Department) query. uniqueResult (); Set
 
  
Set = de. getEmployees (); Iterator it = set. iterator (); while (it. hasNext () {Employee e = (Employee) it. next (); System. out. println (e. getName () ;}}// query the Department by employee @ org. junit. testpublic void getEmployee () {session = HibernateSessionFactory. getSession (); String hql = "FROM Employee e where e. id = 1 "; Query query = session. createQuery (hql); Employee e = (Employee) query. uniqueResult (); System. out. println (e. getName () + "Belong to" + e. getDepartment (). getName ();} // unassociate, which means that an employee leaves the original department and does not delete data in two tables. // Delete @ org from the employee. junit. testpublic void removeRelation () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {Department de = new Department (); de. setId (1); de. setName ("Propaganda Department"); session. save (de); Employee e = (Employee) session. get (Employee. class, 3); e. setDepartment (de); session. save (e); tran. commit ();} Catch (Exception e) {tran. rollback () ;}// Delete employee @ org. junit. testpublic void deleteEmployee () {session = HibernateSessionFactory. getSession (); tran = session. beginTransaction (); try {Employee e = (Employee) session. get (Employee. class, 4); session. delete (e); tran. commit ();} catch (Exception e) {tran. rollback () ;}// delete a department @ org. junit. testpublic void deleteDepartment () {session = HibernateSessionFactory. getSe Ssion (); tran = session. beginTransaction (); try {Department de = (Department) session. get (Department. class, 1);/** if there is no associated employee, you can delete * if there is an associated employee and the inverse attribute is true, because the association cannot be maintained, therefore, the deletion will be executed directly, and an exception will occur * if there is an associated Ang and the inverse attribute is false, because the association can be maintained, then, the associated employee's foreign key is set to null. Deleting */session. delete (de); tran. commit () ;}catch (Exception e) {tran. rollback ();}}}
 


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.