hibernate映射many-to-many

多对多(teacher - student)

在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使用中最好转换成一对多的对象模型;Hibernate会为我们创建中间关联表,转换成两个一对多。

<set name="teacher" table="teacher_student">

<key column="teacher_id"/>

<many-to-many class="Student" column="student_id"/>

</set>


teacher

	private int id;
	private String name;
	private Set<Student> student;

student

	private int id;
	private String name;
	private Set<Teacher> teacher;

<hibernate-mapping>

	<class name="com.huawei.domain.Teacher">
		<id name="id" type="java.lang.Integer">
			<column name="id" />
			<generator class="native" />
		</id>
		
		<property name="name" type="java.lang.String">
			<column name="name" length="5" not-null="false" />
		</property>
		
		<set name="student" table="teacher_student">
			<key column="teacher_id"></key>
			<many-to-many class="com.huawei.domain.Student" column="student_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

<hibernate-mapping>

	<class name="com.huawei.domain.Student">
		<id name="id" type="java.lang.Integer">
			<column name="id" />
			<generator class="native" />
		</id>
		
		<property name="name" type="java.lang.String">
			<column name="name" length="5" not-null="false" />
		</property>
		
		<set name="teacher" table="teacher_student">
			<key column="student_id"></key>
			<many-to-many class="com.huawei.domain.Teacher" column="teacher_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

测试:

		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			
			Set<Teacher> tt = new HashSet<Teacher>();
			Teacher t1 = new Teacher();
			t1.setName("t1");
			tt.add(t1);
			
			Teacher t2 = new Teacher();
			t2.setName("t2");
			tt.add(t2);
			
			Set<Student> ss = new HashSet<Student>();
			Student s1 = new Student();
			s1.setName("s1");
			ss.add(s1);
			
			Student s2 = new Student();
			s2.setName("s2");
			ss.add(s2);
			
			t1.setStudent(ss);
			t2.setStudent(ss);
			
			s.save(t1);
			s.save(t2);
			s.save(s1);
			s.save(s2);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			if(s != null){
				HibernateSessionFactory.closeSession();
			}
		}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值