上次说完了多对一的关系,这次我们来说说一对多
有了上次多对一的理解,一对多理解起来并不难,一对多就是一个老师能教育多个学生。
同样的
MyBatis中在处理一对多的sql语句方式有两种,一种是以子查询的方式,另一种是联表查询
子查询sql语句简单,但是映射关系相对复杂
下面是在MyBatis中StudentMapper.xml用子查询方式进行一对多查询
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id=#{id};
</select>
<!--下面的ofType指的是泛型中的类型
1. JavaType 用来指定实体类中属性的类型
2. ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!
column="id" 这里的id是查询老师表中id mybatis能够通过这个自动匹配到下面查询学生表中的id
-->
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList"
ofType="Student" select="StudentByTeacherId" column="id"/>
</resultMap>
<select id="StudentByTeacherId" resultType="Student">
select *from mybatis.student where tid=#{id};
</select>
联表查询多对一关系是最常用的,也是我最喜欢的,和子查询不同的是,sql语句复杂,但是映射关系逻辑简单,思路清晰
下面是在MyBatis中StudentMapper.xml下配置的联表查询操作
<mapper namespace="com.wcz.dao.StudentMapper">
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,s.tid,t.id tid,t.name tname,t.pwd from student s,teacher t where s.tid = t.id and t.id=#{id};
<!-- javaType & ofType
1. ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!
-->
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<result property="pwd" column="pwd"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
注意点:
原文:https://www.cnblogs.com/myblogswcz/p/12624093.html