1-n association ing and hibernate1-n ing in Hibernate

Source: Internet
Author: User

1-n association ing and hibernate1-n ing in Hibernate
1. 1-N Association ing of Hibernate

1. Which side is 1 and which side is more?

From the business perspective. For example, the relationship between Employee and Department is n-1, and the relationship between Order and Customer is n-1.

1). the link has a direction:
2). How to establish associations in the class? Solution: Use the member variable method.

2. Unidirectional n-1 Association

1) In the domain object, declare a member variable of the Customer type in Order and provide setter and getter

Public class Order {

Private Integer orderId;
Private String orderName;

Private Customer customer;

//...
}

2). Data Table:



3). How to map: Map by using role-to-one

①. Note: foreign key columns need to be mapped to the ORDERS data table!

<Role-to-one name = "customer"
Column = "CUSTOMER_ID"
Class = "Customer"> </role-to-one>

4). API operation
①. When saving, if Order is saved first and the Customer is saved, there will be more UPDATE statements. If the Customer is saved first and then the Order is saved, only INSERT will exist. we recommend that you first save the objects at one end of 1.

②. In get,
◆ By default, the associated objects adopt a lazy loading policy. That is, when Order is obtained, if the attribute of the associated Customer is not used, the Customer object is not loaded.
◆ If there is a LazyInitializationException, the following error may occur: org. hibernate. LazyInitializationException. ◇When is a lazy loading exception?Get an object without initializing its associated attributes. If the Session is closed and the associated attributes are accessed, a lazy loading exception is thrown.

③. During update,
◆ If the object itself is a persistent object, the attributes of the associated object will be updated cascade during the flush Session.
◆ If the object is a free object, the attributes of the associated object will not be updated. However, you can set the cascade attribute to update it.

④. When deleting,
◆ Delete an object. Only the ID attribute is required.
◆ Prevent exceptions caused by foreign key constraints

3. Unidirectional 1-n Association

1). domain object: Add set attributes

Public class Customer {

Private Integer customerId;
Private String customerName;

// Access the set attribute at one end of n
Private Set <Order> orders = new HashSet <> ();

//....
}

Note:
①. When the Session loads a Java set from the database, an instance of the built-in collection class of Hibernate is created,
Therefore, when defining a set attribute in a persistence class, the attribute must be declared as a Java interface type.
②. When defining a set attribute, it is usually initialized as an instance of the set implementation class.
NullPointerException is thrown to avoid the collection of null values during application access.


2). Relational Data Model


3). How to map data by using the set element in Customer. hbm. xml

<Set name = "orders" table = "ORDERS"
Order-by = "ORDER_NAME ASC">
<Key column = "CUSTOMER_ID"> </key>
<One-to-define class = "Order"/>

</Set>

4) Specific API operations:

①. When saving: because one end maintains the association, there will be more UPDATE statements! It is better not to have one end to maintain the association.
②. During update:
◆ If the set object is clear, the foreign key at multiple ends is left blank by default.
③. Delete: You can delete one end, but leave the foreign key of multiple ends empty.

5). order-by attribute of set: You can specify to sort by the columns of the data table corresponding to the set element when querying the set!

<Set name = "orders" table = "ORDERS"
Order-by = "ORDER_NAME ASC">
<Key column = "CUSTOMER_ID"> </key>
<One-to-define class = "Order"/>
</Set>





---------------------------------------------------- Bidirectional Association ing -----------------------------------------------------
4. Bidirectional 1-n Association

1). How to map (The following is the Customer table, pay attention to the relationship between the two)



2 ). the inverse attribute of the set element specifies which Party maintains the association. Generally, in a bidirectional 1-n Association, the inverse of the set at one end of 1 is set to true, indicates that there are n ends to maintain the Association!
◆ For example, in the Customer table:
<Set name = "orders" table = "ORDERS"
Order-by = "ORDER_NAME ASC" inverse = "true">
<Key column = "CUSTOMER_ID"> </key>
<One-to-define class = "Order"/>
</Set>

In hibernate, since the 1-n bidirectional ing does not control the association between the 1 end, what is the use of this bidirectional ing? Isn't it the same as n-1?

User {
Set <Order> orders;
}

Order {
User user;
}

Generally, Order is used to control the relationship. That is, the user configuration <set name = "orders" inverse = "true">
Inverse = "true" means to ask the other party to control the relationship. That is, (the User does not control the relation and the Order Control relation)

That is, if order. setUser (user) is modified, the database is updated.
If we modify user. getOrders (). add (order), the database will not be updated.

As for how the two-way representation is achieved, when we retrieve the user from the database, we can directly use user. getOrders ()
There will be the order we have added.

Hibernate has several mappings.

There are several types of Hibernate ing relationships:

1. Unidirectional N-1

2. Unidirectional 1-1

3. Unidirectional 1-N

4. Unidirectional N-N

5. Bidirectional 1-N

6. Bidirectional N-N

7. Bidirectional 1-1

The following is a simple summary of the seven associations:

I. One-way multi-to-one

View two POJO

Public class Person {

Private int pid;

Private String name;

Private Address address;

... // Generate the corresponding getter and setter Methods

}

----------------------------------------

Public class Address {

Private int id;

Private String detail;

... // Generate the corresponding getter and setter Methods

}

Here we need to maintain the relationship is that multiple persons can correspond to the same address, using a one-way N-1 ing we only need to add a foreign key at one end to one end.

** View the configuration file

<Class name = "Person">

<Id name = "id">

<Generator class = "native"/>

</Id>

... // Some field configurations are omitted

<Your-to-one name = "address" column = "addressId"/> // key Configuration

</Class>

After this configuration, hibernate will add a foreign key SSID to point to one end at one end (Person ).

2. Unidirectional 1-1 (foreign key Association)

You can use the <sequence-to-one> label to specify unique = true for multiple ends. This limits the uniqueness of multiple ends.

Ing one-to-one unique foreign key association using this method

You only need to modify the configuration file:

<Your-to-one name = "address" column = "addressId" unique = "true"/>

3. Unidirectional 1-N

** Looking at the code, we know that a class has multiple students. This is a typical 1-N relationship.

Public class Classes {
Private int id;
Private String name;
Private Set students;

... // Generate the corresponding getter and setter Methods

}

---------------------------------------------------------------------------

Public class Student {
Private int id;
Private String name;

.. // Generate the getter and setter methods.

}

** Ing principle: One-to-Multiple Association ing adds a foreign key to one end on multiple ends, and maintains a link pointing to multiple

** Configuration file:

<Class name = "Classes" table = "t_classes">
<Id ...... remaining full text>

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.