I. federated primary key classes
Joint primary keys are determined by multiple attributes.
Therefore, you need to create a primary key class.
1. Serializable // The primary key needs to be passed
2. equals (Object o) // identify the primary key based on the primary key, so it is required
3. hashCode () // search based on the pk's hash code, so it is required
[Java]
Public class TeacherPK implements Serializable
{
Private int id;
Private String name; // generate a primary key based on the two attributes.
Public boolean equals (Object o) // The primary key is used to distinguish between primary keys. Therefore
{
If (o instanceof TeacherPK)
{
TeacherPK pk = (TeacherPK) o; // strong Conversion
If (this. id = pk. getId () & this. name. equals (pk. getName ()))
{
Return true; // both id and name are equal, which is the same primary key.
}
}
Return false; // return false for all other cases
}
Public int hashCode () // search by the pk hash code, so it must
{
Return this. name. hashCode ();
}
// Setter & getter
Ii. Annotation
1. Write @ Embeddable on TeacherPK
Write @ Id on the aggregate getPk ()
2. Write @ EmbeddedId on getPk ()
3. @ IdClass (value = TeacherPK. class)
@ Id is required for both name and Id.
[Java]
@ Entity
@ Table (name = "t_Teacher ")
Public class Teacher {
Private TeacherPK pk; // aggregate the Union primary key
Private int age;
Private Date birthday;
Private String secret;
Private Grade grade;
// Setter & getter
@ EmbeddedId // write EmbeddedId on the getPK () method of the joint primary key
Public TeacherPK getPk (){
Return pk;
}
Iii. JUnit Testing
[Java]
Session session = HibernateUtil. getSessionFactory (). getCurrentSession ();
Session. beginTransaction ();
TeacherPK pk = new TeacherPK (); // assemble the Union primary key
Pk. setId (250 );
Pk. setName ("James ");
Teacher t = new Teacher ();
T. setPk (pk); // set Union primary key
T. setAge (0 );
T. setBirthday (new Date ());
T. setGrade (Grade. );
Session. save (t );
Session. getTransaction (). commit ();
HibernateUtil. getSessionFactory (). close ();
After execution, the primary key is: primary key (id, name)
DEBUG SchemaUpdate: 226-create table t_Teacher (id number (255) not null, name varchar2 (char) not null, age number () not null, birthday date, grade varchar2 (255 char), primary key (id, name ))