[Java]
Multiple students ------ multiple teachers
1. Java files: [omitting the set and get methods]
Student. java
Public class Student {
Private int id;
Private String name;
Private Set <Teacher> teas;
}
Teacher. java
Public class Teacher {
Private int id;
Private String name;
Private Set <Student> stus;
}
2. Xml ing file:
Student. hbm. xml:
<? Xml version = "1.0"?>
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 3.0 // EN"
"Www.2cto.com">
<Hibernate-mapping
Package = "cn. hibernate. model">
<Class name = "Student" table = "student">
<Id name = "id">
<Generator class = "native"/>
</Id>
<Property name = "name" column = "name"/>
<! -- The corresponding table is teacher_student -->
<Set name = "teas" table = "teacher_student">
<! -- First find student_id -->
<Key column = "student_id"> </key>
<! -- Then locate teacher_id and find teacher -->
<Role-to-operate class = "Teacher" column = "teacher_id"> </role-to-operate>
</Set>
</Class>
</Hibernate-mapping>
Teacher. hbm. xml
<? Xml version = "1.0"?>
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 3.0 // EN"
"Www.2cto.com">
<Hibernate-mapping
Package = "cn. hibernate. model">
<Class name = "Teacher" table = "teacher">
<Id name = "id">
<Generator class = "native"/>
</Id>
<Property name = "name" column = "name"/>
<Set name = "stus" table = "teacher_student">
<! -- Foreign key, the instructor table according to teacher_id -->
<Key column = "teacher_id"> </key>
<! -- Set the matched many-to-many relationship and the primary key of the other party -->
<Role-to-train class = "Student" column = "student_id"> </role-to-train>
</Set>
</Class>
</Hibernate-mapping>
3. insert an automatic table generation operation:
// Add employee and IDcard
Static void AddTeacherAndStudent (){
Session s = null;
Transaction tx = null;
Try {
Student stu = new Student ();
Set <Teacher> ts = new HashSet <Teacher> ();
Set <Student> ss = new HashSet <Student> ();
S = HibernateUtil. getSession ();
Tx = s. beginTransaction ();
Teacher t1 = new Teacher ();
Ts. add (t1 );
Teacher t2 = new Teacher ();
Ts. add (t2 );
Student s1 = new Student ();
Ss. add (s1 );
Student s2 = new Student ();
Ss. add (s2 );
// Tea. setStus (sets );
// Stu. setTeas (sett );
T1.setName ("t1 ");
T2.setName ("t2 ");
S1.setName ("s1 ");
S2.setName ("s2 ");
T1.setStus (ss );
S. save (t1 );
S. save (t2 );
S. save (s1 );
S. save (s2 );
Tx. commit ();
} Catch (HibernateException e ){
// Determine whether the transaction is fully committed.
If (tx! = Null ){
Tx. rollback ();
Throw e;
}
} Finally {
If (s! = Null ){
S. close ();
}
}
}
Author: zhang6622056