Java programmers from stupid birds to cainiao (60) detailed discussion on Hibernate (11) hibernate composite primary key ing

Source: Internet
Author: User

Welcome to other blogs on this topic:

Discuss hibernate (6) hibernate inheritance relationship ing

 

About hibernate (7) one-to-many and many-to-many

 

A closer look at hibernate (8) map the map relationship in the hibernate set

 

Hibernate (9) one-to-one relationship ing

 

About hibernate (10) Hibernate query sorting and component ing

 

The so-called composite primary key is in a database table, where there are two or more primary keys. This situation occurs during daily development, A table in the database requires multiple field columns to uniquely identify a row of records. In this case, the table needs to use a composite primary key. This is a situation we have never encountered in hibernate configuration before. In the face of such a situation, Hibernate provides us with two ways to solve the problem of compound primary keys. Let's take a look at these two situations:

 

1: Put the attributes corresponding to the composite primary key together with other common attributes of the object.

2: extract the primary key attribute to a primary key class. The entity class only needs to include a reference of the primary key class.

 

Let's take a look:

 

Method 1: Put the attributes corresponding to the composite primary key together with other common attributes of the object

For example, the "ID" and "name" attributes in the object class people correspond to the composite primary key:

 

/* Entity class, must implement the serializable interface */public class people implements serializable {private string ID; private string name; private int age; Public people () using the composite primary key () {} *************** set, get method public int hashcode () {final int prime = 31; int result = 1; result = prime * result + (ID = NULL )? 0: Id. hashcode (); Result = prime * result + (name = NULL )? 0: Name. hashcode (); return result ;}@ override public Boolean equals (Object OBJ) {If (this = OBJ) return true; If (OBJ = NULL) return false; if (getclass ()! = Obj. getclass () return false; People Other = (people) OBJ; If (ID = NULL) {If (other. ID! = NULL) return false;} else if (! Id. Equals (other. ID) return false; If (name = NULL) {If (other. Name! = NULL) return false;} else if (! Name. Equals (other. Name) return false; return true ;}}

 

People. HBM. xml:

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype hibernate-mapping public "-// hibernate/hibernate DTD ing DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

When using a composite primary key in hibernate, pay attention to the following rules:

1. The object class using the composite primary key must implement the serializable interface. The reason why the serializable interface must be implemented is simple. When we look for data, we find data based on the primary key. Open the help document of Hibernate and we can find the declaration form of the get and load methods as follows:

Object load(Class theClass,Serializable id)Object get(Class theClass,Serializable id)

When we look for objects in the composite primary key class, we need to pass the primary key value to the ID parameter of the get () or load () method, the ID parameter can only receive one object that implements the serializable interface. The primary key of the composite primary key class is not an attribute that can be expressed. Therefore, only instances of the composite primary key class (such as new people () can be created first ()), then, the Set Method of the primary key attribute is used to assign the primary key value to the primary key attribute, and then the entire object is passed to the ID parameter of the get () or load () method to transfer the primary key value, therefore, the entity class of the composite primary key must implement the serializable interface.

 

2. make it necessary to rewrite the equals and hashcode methods for the entity class with the composite primary key. The equals and hashcode methods must be rewritten. These two methods are used to determine whether two objects (two records) are equal. Why do we need to determine whether two objects are equal? Because the primary key values of any two records in the database cannot be the same, we only need to ensure that the primary key values of the two objects are different in the program to prevent primary key constraint violation errors. You may wonder why the entity classes that do not use the composite primary key do not override these two methods, and there is no primary key violation. This is because a single
The primary key value is maintained by hibernate, which ensures that the primary key will not be repeated. The primary key value is maintained by the programmer, therefore, the equals and hashcode methods must be rewritten to determine whether the primary keys of the two objects are the same.

 

3. The rewritten equals and hashcode methods are only related to primary key attributes. Normal attributes do not affect the two methods for determination. This is because the primary key determines a record, and other attributes cannot determine a record.

 

Save test:

Tx = session. begintransaction (); People = new people ();/* The primary key value is maintained by ourselves */people. setid ("123456"); people. setname ("zhangsan"); people. setage (40); Session. save (people); Tx. commit ();

Look at the database:

The data is correctly inserted into the database.

 

Test data reading:

Tx = session. begintransaction ();/* to query the composite primary key object, you must first construct the primary key */People peopleprimarykey = new people (); leleprimarykey. setid ("123456"); leleprimarykey. setname ("zhangsan");/* then pass the constructed primary key value to the get method to obtain the corresponding people object */People people = (people) session. get (people. class, leleprimarykey); system. out. println ("people age is:" + people. getage (); Tx. commit ();

Console output: People age is: 40, to see that the data is successfully retrieved.

 

Method 2: extract the primary key attribute to a primary key class. The entity class only needs to include a reference of the primary key class.

Primary Key class:

/* Must implement the serializable interface */public class peopleprimarykey implements serializable {/* compound primary key value */private string ID; private string name; Public peopleprimarykey () {}/* The get and set methods of the composite primary key values are omitted here */@ override public int hashcode () {final int prime = 31; int result = 1; result = prime * result + (ID = NULL )? 0: Id. hashcode (); Result = prime * result + (name = NULL )? 0: Name. hashcode (); return result ;}@ override public Boolean equals (Object OBJ) {If (this = OBJ) return true; If (OBJ = NULL) return false; if (getclass ()! = Obj. getclass () return false; leleprimarykey Other = (leleprimarykey) OBJ; If (ID = NULL) {If (other. ID! = NULL) return false;} else if (! Id. Equals (other. ID) return false; If (name = NULL) {If (other. Name! = NULL) return false;} else if (! Name. Equals (other. Name) return false; return true ;}}

Entity class:

Public class people {/* holds a reference to the primary key class and uses this reference as the oId of this class */private peopleprimarykey; private int age; Public people () {} *************************** set/get method omitted}

 

The people. HBM. xml file is slightly changed:

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype hibernate-mapping public "-// hibernate/hibernate DTD ing DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

The same is true for scenario tests and methods. The reason why the primary key class implements the serializable interface and why the equals and hashcode rewrite methods have been explained clearly above.

 

3. Join primary key ing rules

1) Each primary key attribute in the class corresponds to each primary key column in the data table. Hibernate requires the entity class with the joint primary key to implement the serializable interface and override the hashcode and equals methods, the reason for rewriting these two methods is that hibernate judges whether the records of a certain two rows are the same based on the database's joint primary key. If the record is the same, the record is considered to be the same object. If the record is different, it is considered to be different objects. This is reflected in the program field by judging whether two objects can be put into a set such as set based on the hashcode and equals methods.The reason why the object class of the joint primary key implements the serializable interface is that when using the get or load method, you need to first build the object of the object and set the query basis (joint primary key, then, it is passed as the second parameter of the get or load method.

2) extract a class (called a primary key class) from the attribute corresponding to the primary key, and implement the serializable interface for the primary key class. Rewrite the equals and hashcode methods for the same reason as above.

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.