首页 > 程序开发 > 软件开发 > Java >

Hibernate入门BLOG[十、Hibernate对象关系多对多映射]

2012-06-26

[java]多学生------多教师1、 Java类文件:【省略set和get方法】Student.javapublic class Student { private int id; private String name; private Set<Teacher> teas;}Teacher.javapublic clas...

[java]
多学生------多教师
1、 Java类文件:【省略set和get方法】
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映射文件:

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"/>
<!-- 对应的table是teacher_student -->
<set name="teas" table="teacher_student">
<!-- 首先找到student_id -->
<key column="student_id"></key>
<!-- 然后找到teacher_id找到teacher -->
<many-to-many class="Teacher" column="teacher_id"></many-to-many>
</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">
<!-- 外键,老师表根据teacher_id -->
<key column="teacher_id"></key>
<!-- 设置匹配的多对多的关系和另一方的主键 -->
<many-to-many class="Student" column="student_id"></many-to-many>
</set>

</class>
</hibernate-mapping>

3、 插入自动生成表操作:
//添加员工和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){
//判断事务有没有完全提交的判断方式
if(tx != null){
tx.rollback();
throw e;
}
}finally{
if(s != null){
s.close();
}
}
}
作者:zhang6622056
相关文章
最新文章
热点推荐