mybaits的一对多,多对一实现
多对一
一个老师有5个学生 【集合】
5个学生关联一个老师【关联】 多对一的时候resultMap里面不用result去一一对应查询sql的表列和实体类属性名称了。多的那一项要用 association【可以理解为一个对象】



方法一:通过子查询的方法来
思路:先查Student信息,根据查出来Student的tid 子查询查询Teacher数据

<select id="getTeacherList" resultType="teacher"> select * from mybaits.teacher where id=#{id} </select> <select id="getStudentList" resultMap="studentlist"> select * from mybaits.student </select> <resultMap id="studentlist" type="student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" javaType="teacher" select="getTeacherList"/> </resultMap>
方法二:关联查询
<!--嵌套查询,先查a表数据再把b表的数据直接association再使用result将属性值和查询出的b表数据--> <select id="getStudentList1" resultMap="studentlist1"> select a.id sid,a.name sname ,b.name tname from mybaits.student a, mybaits.teacher b where a.tid=b.id </select> <resultMap id="studentlist1" type="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="teacher"><!--这里可以理解为【多对一】【一】代表的是一个对象,javaType是对象的类 -->
<!--因为这里没有管teacher的id,所以查询结果id都是默认值0-->
<result property="name" column="tname"/> </association> </resultMap>
一对多:
一对多用:collection
一对多可以理解为一个对象,一个列表



总结:
多对一:关联 association
一对多:集合 collection
javaType:用于指定实体类中属性的类型
ofType:用于指定映射到集合或者list中的pojo实体类型 泛型中的约束类型

浙公网安备 33010602011771号