hibernate多表联查:多对多关联

以Student学生对像与Teacher老师对像间多对多关联为例
步骤:
	1.需要中间表来维护多对多关系
	2.在Student类中有Set<Teacher>,在Teacher类中有Set<Student>
	3.在Mapper文件中使用<Set>标签及子标签<many-to-many>来配置映射关系
//Student类
public class Student {
	private Integer id;
	private String sname;	
	//多对多
	private Set<Teacher> teaches;   
}
//Teacher类
public class Teacher {
	private Integer id;
	private String tname;
	//多对多
	private Set<Student> stus;
<!--Student.hbm.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="join.model.Student" table="STUDENT">
		<id name="id" column="ID">
			<generator class="increment"></generator>
		</id>
		<property name="sname" column="SNAME"></property>
		
		<!-- 多对多 -->
        <!--
			table:用来指定中间表的名称
		-->
		<set name="teaches" table="STU_TEACH">
			<!-- 从学生表到中间表的外键关系 -->
			<key column="SID"></key>
			<!-- 从中间表到被关联Teacher表的外键 -->
			<many-to-many class="join.model.Teacher" column="TID"></many-to-many>
		</set>
	</class>
</hibernate-mapping>
<!--Teacher.hbm.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="join.model.Teacher" table="TEACHER">
		<id name="id" column="ID">
			<generator class="increment"></generator>
		</id>
		<property name="tname" column="TNAME"></property>
		
		<!-- 多对多 -->
		<set name="stus" table="STU_TEACH">
			<key column="TID"></key>
			<many-to-many class="join.model.Student" column="SID"></many-to-many>
		</set>
	</class>
</hibernate-mapping>
//StudentDao
public class StudentDao {

	public Student selectById(Integer id){
		
		Session session = HibernateUtil.findSession();
		
		return session.get(Student.class, id);
	}
}
//StudentService
public class StudentService {

	private StudentDao dao = new StudentDao();

	public Student findById(int id) {

		Session session = HibernateUtil.findSession();
		Transaction tx = session.beginTransaction();
		Student stu = null;
		try {
			stu = dao.selectById(id);
			// tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}
		return stu;
	}
}
   //测试
	@Test
	public void testFindStudent() {
        
        StudentService ser = new StudentService();

		Student stu = ser.findById(1);
		//多对多:关联出所有老师信息
        //反过来,查询单个老师,也可以同时关联出学生集合对像(略)
		System.out.println(stu.getTeaches());
	
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值