Hibernate bidirectional 1-n (detailed analysis)

Source: Internet
Author: User
Tags generator

    • Bidirectional 1-n and bidirectional n-1 are exactly the same two situations
    • Bidirectional 1-n need to be at one end of the 1 to access the end of N, and vice versa.
    • Domain Model: A Many-to-one bidirectional association from order to customer needs to define a customer property in the Order class, and in the Customer class, you define the collection property that holds the order object

    • Relational data Model: The CUSTOMER_ID in the ORDERS table references the primary key of the CUSTOMER table

    • Attention:
When a
Session loads a Java collection from a database, it creates an instance of the Hibernate built-in collection class, so you must declare the property as a Java interface type when defining the collection property in a persisted class
Hibernate's built-in collection classes have a collection agent feature that supports deferred retrieval strategies in fact, Hibernate's built-in collection classes encapsulate the collection classes in the JDK, which allows Hibernate to dirty-check the collection objects in the cache and update the database synchronously by the state of the collection object.
When you define a collection property, you typically initialize it to an instance of the collection implementation class. This can improve the robustness of the program and prevent the application from accessing a null-valued collection of methods thrown NullPointerException

    • Hibernate uses the <set> element to map the properties of a set type

    • Set
    • Key
    • One-to-many:

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 collection type, the interface type is used, because hibernate returns hibernate when it gets the * collection type Built-in collection type, rather than javase a standard * collection implementation.  * 2. The collection needs to be initialized to prevent null pointer exceptions */private set<order> orders = new hashset<> ();p ublic 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<order> getorders () {return orders;} public void Setorders (set<order> 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
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
Order.hbm.xml
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

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 = new Configuration (). Configure ();                            Serviceregistry serviceregistry = new Serviceregistrybuilder (). Applysettings (Configuration.getproperties ()) . Buildserviceregistry (); sessionfactory = Configuration.buildsessionfactory (serviceregistry); session = Session Factory.opensession (); transaction = 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 () {//In the case that there is no cascading relationship, and the object at this end of 1 has an object of n being referenced, you cannot directly delete the object at the end of the 1 customer customer = (customer) session. Get (Customer.class, 1); Session.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 lazy loading for a collection of one end of n the customer customer = (customer) session.get (Customer.class, 7); System.out.println (Customer.getcustomername ()); 2. Returns a collection of multiple ends when Hibernate is built into the collection type. This type has the ability to delay loading and storing proxy objects. System.out.println (Customer.getorders (). GetClass ()); Session.close ();//3. Lazyinitializationexception exceptions may be thrown System.out.println (Customer.getorders (). Size ()); 4. You need to initialize the elements in the collection again. } @Testpublic void Testmany2oneget () {//1. If you query an object at one end of a multiple, the defaultCase, only the objects at one end of the query are queried. Without querying the object associated with that end of the//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 when the associated object needs to be used. Customer customer = Order.getcustomer (); System.out.println (Customer.getcustomername ()); 3. When querying the Customer object, the lazyinitializationexception exception//4 will occur by default//If the one end of the multiple is navigated to one end of 1//If the session is closed at this time. When you get the Order object, by default, its associated Customer object is a proxy object!} @Testpublic void Testmany2onesave () {Customer customer = new Customer (); Customer.setcustomername ("AA"); Order order1 = New Order (); Order1.setordername ("ORDER-1"); Order Order2 = New Order (); Order2.setordername ("ORDER-2");// Sets the association relationship order1.setcustomer (customer); Order2.setcustomer (customer); Customer.getorders (). Add (Order1); Customer.getorders (). Add (order2);//Perform the save operation: First insert Customer, then insert Order, 3 inserts, 2 update//because one end of 1 and the other side of N maintain the correlation relationship. So there will be more update//. You can specify inverse=true on the set node at one end of the 1 to give the end of the 1 to the Maintenance association!//it is recommended that set inVerse=true, it is recommended to first insert one end of the 1, and then insert many of the end//benefit is not more than the UPDATE statement session.save (customer);//session.save (order1);//session.save ( ORDER2);//First insert Order, then insert 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.