Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Hibernate Association relationship

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to realize Hibernate association". In daily operation, I believe many people have doubts about how to realize Hibernate association. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "how to realize Hibernate association". Next, please follow the editor to study!

One-to-many one-way association

[@ more@]

First, set up the Customer and Order classes, as follows:

Customer class:

Package mypack

Import java.io.Serializable

Import org.apache.commons.lang.builder.ToStringBuilder

Public class Customer implements Serializable {

Private Long id

Private String name

Public Customer (String name) {

This.name = name

}

Public Customer () {

}

Public Long getId () {

Return this.id

}

Public void setId (Long id) {

This.id = id

}

Public String getName () {

Return this.name

}

Public void setName (String name) {

This.name = name

}

Public String toString () {

Return new ToStringBuilder (this)

.append ("id", getId ())

.toString ()

}

}

Order class:

Package mypack

Import java.io.Serializable

Import org.apache.commons.lang.builder.ToStringBuilder

Public class Order implements Serializable {

Private Long id

Private String orderNumber

Private mypack.Customer customer

Public Order (String orderNumber, mypack.Customer customer) {

This.orderNumber = orderNumber

This.customer = customer

}

Public Order () {

}

Public Order (mypack.Customer customer) {

This.customer = customer

}

Public Long getId () {

Return this.id

}

Public void setId (Long id) {

This.id = id

}

Public String getOrderNumber () {

Return this.orderNumber

}

Public void setOrderNumber (String orderNumber) {

This.orderNumber = orderNumber

}

Public mypack.Customer getCustomer () {

Return this.customer

}

Public void setCustomer (mypack.Customer customer) {

This.customer = customer

}

Public String toString () {

Return new ToStringBuilder (this)

.append ("id", getId ())

.toString ()

}

}

The configuration files for the Customer and Order classes are Customer.hbm.xml and Order.hbm.xml, respectively

Customer.hbm.xml is as follows:

Id >

Property >

Class >

Order.hbm.xml is as follows:

Id >

Property >

Class >

Hibernate-mapping >

The element in Order.hbm.xml establishes the relationship between Customer and the foreign key CUSTOMER_ID of the ORDERS table

The mapping of.

It includes the following properties.

● name: sets the property name of the persistent class to be mapped, here is the customer property of the Order class.

● column: sets the foreign key of the table corresponding to the property of the persistence class, in this case, the foreign key CUSTOMER_ID of the ORDERS table.

● class: sets the type of the property of the persistence class, where the customer property is set to the Customer class.

● not-null: if ture, the customer attribute cannot be null. The default is false.

Next, we persist a Customer object and the Order object associated with it:

(the following code is not complete, but simply lists the logic.)

Configuration config = new Configuration ()

Config.addClass (Customer.class)

. AddClass (Order.class)

SessionFactory = config.buildSessionFactory ()

Session session = sessionFactory.openSession ()

Transaction tx = null

Tx = session.beginTransaction ()

Customer customer=new Customer ("Jack")

Session.save (customer)

Order order1=new Order ("Jack_Order001", customer)

Order order2=new Order ("Jack_Order002", customer)

Session.save (order1)

Session.save (order2)

Tx.commit ()

When we want to persist a Customer object and the Order object associated with it, we must first create a Customer object and persist it, otherwise an exception will be thrown when creating an Order persistent object, if session.save (customer)

Logging out will throw a PropertyValueException exception in session.save (order1). Analyze the cause of the exception: before calling the session.save (order1) method, both order1 and customer objects are temporary objects, which have just been created with new but have not been persisted yet, and Hibernate does not automatically persist the customer objects associated with order1, which means that only one record is inserted into the ORDERS table in the database, and the CUSTOMER_ID field of the record is null, which violates the database integrity constraint Because the CUSTOMER_ID field of the ORDERS table is not allowed to be null.

You can see from the above example that when Hibernate persists a temporary object, by default, it does not automatically persist other temporary objects associated with it, so it throws a PropertyValueException exception. If you want to automatically persist the associated Order object when Hibernate persists the Customer object, you can set the cascade property to "save-update" and the cascade property to "none" by default:

This makes it possible to automatically persist the associated Order object when Hibernate persists the Customer object.

Second, one-to-many two-way association.

We still use the previous examples of Customer and Order. Because it is a two-way association, the Order class code is the same as above, and because there is an associated object of Order in the Customer class, the Customer class is changed to the following:

Package mypack

Import java.io.Serializable

Import java.util.Set

Import org.apache.commons.lang.builder.ToStringBuilder

Public class Customer implements Serializable {

Private Long id

Private String name

Private Set orders

Public Customer (String name, Set orders) {

This.name = name

This.orders = orders

}

Public Customer () {

}

Public Customer (Set orders) {

This.orders = orders

}

Public Long getId () {

Return this.id

}

Public void setId (Long id) {

This.id = id

}

Public String getName () {

Return this.name

}

Public void setName (String name) {

This.name = name

}

Public Set getOrders () {

Return this.orders

}

Public void setOrders (Set orders) {

This.orders = orders

}

Public String toString () {

Return new ToStringBuilder (this)

.append ("id", getId ())

.toString ()

}

}

How do you map the order attribute of a collection type in a mapping file? Since there are no fields in the CUSTOMERS table that directly correspond to the order attribute, you cannot map the order attribute with an element, but rather use an element:

The element also contains two child elements: and, the element sets the associated persistence class, in this case, the Order class, and the element sets the foreign key of the table corresponding to the associated persistence, in this case the CUSTOMERS_ID field of the ORDERS table.

It includes the following properties:

The ● element indicates that the orders attribute of the Customer class is of the java.util.Set collection type.

● indicates that a set of Order objects is stored in the orders collection.

The ● attribute indicates that the ORDERS table references the CUSTOMERS table through the foreign key CUSTOMERS_ID.

The value of the ● cascade property is "save-update", indicating that when a Customer object is saved or updated, all Order objects in the orders collection are cascaded or updated.

Next, we persist a Customer object and the Order object associated with it:

Session session = sessionFactory.openSession ()

Transaction tx = null

Tx = session.beginTransaction ()

Customer customer=new Customer ("Tom", new HashSet ())

Order order=new Order ()

Order.setOrderNumber ("Tom_Order001")

Order.setCustomer (customer)

Customer.getOrders () add (order)

Session.save (customer)

Tx.commit ()

When the element's cascade attribute is "save-update", Hibernate automatically persists the associated Customer object when it persists the Order object.

What if you load a persistent object and then establish an association? As follows:

Session session = sessionFactory.openSession ()

Transaction tx = null

Tx = session.beginTransaction ()

Customer customer= (Customer) session.load (Customer.class,new Long (2))

Order order= (Order) session.load (Order.class,new Long (2))

Order.setCustomer (customer)

Customer.getOrders () add (order)

Tx.commit ()

Hibernate automatically cleans up all persistent objects in the cache and updates the database synchronously according to persistent object state changes. Hibernate executes the following two SQL statements when cleaning the above Customer objects and Order objects:

Update ORDERS set ORDER_NUMBER='Jack_Order001',CUSTOMER_ID=2 where ID=2

Update ORDERS set CUSTOMER_ID=2 where ID=2

Although only one record of the ORDERS table has been modified, the above SQL statement shows that Hibernate performed two update operations because HIbernate determines the SQL statement to be executed according to the state change of the persistent object in memory, and the corresponding SQL statement executed by order.setCustomer (customer) is:

Update ORDERS set ORDER_NUMBER='Jack_Order001',CUSTOMER_ID=2 where ID=2

The corresponding SQL statement executed by customer.getOrders () .add (order) is:

Update ORDERS set CUSTOMER_ID=2 where ID=2

Repeated execution of the SQL statement for will affect the performance of the application, so the solution is to set the element's inverse property to true, which defaults to false:

Set >

Therefore, when mapping one-to-many two-way associations, you should set the inverse property to "ture" on the "one" side, which can improve performance.

Third, one-to-many two-way self-correlation

Take food as an example, it represents the category of goods, and there is an one-to-many two-way self-correlation. As shown in the following figure, the fruit category belongs to the food category, and it also contains two subcategories: the apple category and the orange category.

Each item in the figure represents a Category object, which forms a tree data structure. Every Category

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report