Hibernate bidirectional 1-n (detailed analysis)

Source: Internet
Author: User

Two-way 1-n and two-way N-1 are exactly the same. Two-way 1-n needs to be able to access one end of n at one end. domain model: the multi-to-one bidirectional association between Order and Customer requires a Customer attribute defined in the Order class, And the set attribute of the Order object to be defined in the Customer class.

Relational Data Model: The CUSTOMER_ID in the ORDERS table references the primary key of the CUSTOMER table.

Note:

When a Session loads a Java set from a database, an instance of the Hibernate built-in collection class is created. Therefore, when defining a set attribute in a persistence class, the property must be declared as a Java interface type.
The built-in collection class of Hibernate has the collection proxy function and supports the latency retrieval policy. In fact, the built-in collection class of Hibernate encapsulates the collection class in JDK, which enables Hibernate to perform dirty checks on the collection objects in the cache, synchronously update the database based on the collection object status.
When defining a set attribute, it is usually initialized to an instance of the set implementation class. This can improve the robustness of the program and prevent the NullPointerException from being thrown by the method of the set whose application access value is null.

Use Hibernate Element to map set type attributes

Set:
Key: one-to-operate:

Customer. java
Package com. atguigu. hibernate. entities. n21.both; import java. util. hashSet; import java. util. set; public class Customer {private Integer customerId; private String customerName;/** 1. when declaring a set type, you need to use the interface type, because when hibernate obtains * set type, it returns the built-in set type of Hibernate, rather than a standard * Set Implementation of JavaSE. * 2. the Set needs to be initialized to prevent null pointer exceptions */private Set
  
   
Orders = new HashSet <> (); public Integer getCustomerId () {return customerId;} public void setCustomerId (Integer customerId) {this. customerId = customerId;} public String getCustomerName () {return customerName;} public void setCustomerName (String customerName) {this. customerName = customerName;} public Set
   
    
GetOrders () {return orders;} public void setOrders (Set
    
     
Orders) {this. orders = orders ;}}
    
   
  

Order. java
package com.atguigu.hibernate.entities.n21.both;public class Order {private Integer orderId;private String orderName;private Customer customer;public Integer getOrderId() {return orderId;}public void setOrderId(Integer orderId) {this.orderId = orderId;}public String getOrderName() {return orderName;}public void setOrderName(String orderName) {this.orderName = orderName;}public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}}

Customer. hbm. xml
  
          
               
                
                 
             
                
                
             
                    
            
            
            
            
            
            
             
             
             
             
                
       
  

Order. hbm. xml
  
      
           
                
                 
             
                    
                
             
            
    
        
   
  

Package com. atguigu. hibernate. entities. n21.both; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; import org. hibernate. service. serviceRegistryBuilder; import org. junit. after; import org. junit. before; import org. junit. test; public class HibernateTest {private SessionFactory SessionFactory; private Session session; private Transaction transaction; @ Beforepublic void init () {Configuration configuration Configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry); session = sessionFactory. openSession (); t Ransaction = session. beginTransaction () ;}@ Afterpublic void destroy () {transaction. commit (); session. close (); sessionFactory. close () ;}@ Testpublic void testCascade () {Customer customer = (Customer) session. get (Customer. class, 3); customer. getOrders (). clear () ;}@ Testpublic void testDelete () {// if there is no cascading relationship, and n objects at the end of 1 are being referenced, the Customer customer = (Customer) session object at the end of 1 cannot be directly deleted. get (Customer. class, 1); se Ssion. delete (customer) ;}@ Testpublic void testUpdat2 () {Customer customer = (Customer) session. get (Customer. class, 1); customer. getOrders (). iterator (). next (). setOrderName ("GGG") ;}@ Testpublic void testUpdate () {Order order = (Order) session. get (Order. class, 1); order. getCustomer (). setCustomerName ("AAA") ;}@ Testpublic void testOne2ManyGet () {// 1. use the delayed loading of Customer customer = (Customer) session for the set at one end of n. get (Customer. class, 7); System. out. println (customer. getCustomerName (); // 2. hibernate built-in set type when multiple end sets are returned. // This type has the function of delaying loading and storing proxy objects. system. out. println (customer. getOrders (). getClass (); // session. close (); // 3. the System may throw a LazyInitializationException. out. println (customer. getOrders (). size (); // 4. initialization is required when elements in the set are used .} @ Testpublic void testMany2OneGet () {// 1. if you query an object at multiple ends, only objects at multiple ends are queried by default. no associated query // The object at the end of 1! Order order = (Order) session. get (Order. class, 1); System. out. println (order. getOrderName (); System. out. println (order. getCustomer (). getClass (). getName (); session. close (); // 2. the corresponding SQL statement is sent only when the associated object is used. customer customer = order. getCustomer (); System. out. println (customer. getCustomerName (); // 3. when you query a Customer object and navigate from multiple ends to one end, // if the session is closed, the LazyInitializationException will occur by default. // 4. obtain By default, the associated Customer object is a proxy object !} @ Testpublic void testMany2OneSave () {Customer customer Customer = new customer (); Customer. setCustomerName ("AA"); Order order1 = new Order (); order1.setOrderName ("ORDER-1"); Order order2 = new Order (); order2.setOrderName ("ORDER-2"); // set the association relationship order1.setCustomer (customer); order2.setCustomer (customer); customer. getOrders (). add (order1); customer. getOrders (). add (order2); // execute the save operation: First INSERT Customer, then INSERT Order, 3 INSERT, Two updates // because one end of 1 maintains an association with the other end of n. so there will be more updates // you can specify inverse = true on the set node at the end of 1, so that the end of 1 will not maintain the association relationship! // We recommend that you set inverse to true. We recommend that you first insert one end, and then insert multiple ends. // The advantage is that there will be no more UPDATE statement sessions. save (customer); // session. save (order1); // session. save (order2); // INSERT Order first, then Cusomer, 3 INSERT, 4 UPDATE // session. save (order1); // session. save (order2); // session. save (customer );}}



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.