When two tables (table A and Table B) in the database have many-to-many relationships, an intermediate table (table C) is generally created ), A multi-to-one relationship is formed with tables A and B. The intermediate Table C consists of multiple primary keys that constitute a composite primary key. These primary keys are the foreign keys of tables A and B. The ing of a composite primary key is different from that of a common field. The two methods are as follows:
When two tables (table A and Table B) in the database have many-to-many relationships, an intermediate table (table C) is generally created ), A multi-to-one relationship is formed with tables A and B. The intermediate Table C consists of multiple primary keys that constitute a composite primary key. These primary keys are the foreign keys of tables A and B.
The ing of a composite primary key is a little different from that of a common field. The following two methods are generally used:
Method 1:
Ing code
<Class name = "Simple. Test. User" table = "user">
<Composite-ID>
<Key-property name = "name" column = "name" type = "Java. Lang. String"/>
<Key-property name = "Age" column = "Age" type = "Java. Lang. Integer"/>
</Composite-ID>
.............
</Class>
Create a user object and save it with Session save ().
User user = new user ();
User. setname ("test ");
User. setage ("20 ");
Session. Save (User ):
Method 2: Define a separate primary key class
Ing code
<Class name = "Simple. Test. User" table = "user">
<Composite-ID name = "sysuser" class = "Simple. Test. userpk">
<Key-property name = "name" column = "name" type = "Java. Lang. String"/>
<Key-property name = "Age" column = "Age" type = "Java. Lang. Integer"/>
</Composite-ID>
............
</Class>
Create a user class, a userpk class, and use session save () to save the object of the user class
Some code of userpk. Java:
Public class userpk implements serializable
{
Private string name;
Private int age;
Public userpk (string name, int age)
{
This. Name = Name;
This. Age = age;
}
Public setname (string name )....
Public getname ().....
Public setage (INT age )....
Public getage ()........
..................
}
Some code of user. Java:
Public class user implements serializable
{
Private userpk;
Public user (){}
Public setuserpk (userpk)
{
This. userpk = userpk;
}
Public getuserpk ()
{
Return userpk;
}
....................
}
Userpk = new userpk ("test", "20 ")
Use user = new user ();
User. setuserpk (userpk );
Session. Save (User );
Note:
Both the user class and the independent primary key class require
1. Implement the serializable Interface
2. Override equals () and hashcode () Methods
In addition, you can use some automated methods to generate data. For more information, seeUse hibernate-extensions to automatically generate pojo objects