标签:odi 外键 bsp select 映射 bat encoding 联表查询 查询
1.在一个实体类中添加另一个实体类的属性及List属性:
public class Course {
private int id;// id --> cid
private String name;// name --> cname
private Teacher teacher;
private List<Student> list;
2.定义SQL映射文件courseMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 -->
<mapper namespace="com.mapping.courseMapper">
<!--
方式一:
select * from ksl_course c, ksl_teacher t where c.tid=t.tid and c.cid=1
-->
<select id="getCourse" parameterType="int" resultMap="CourseResultMap">
select * from ksl_course c, ksl_teacher t, ksl_score s1, ksl_student s2 where c.tid=t.tid and c.cid=s1.cid and s1.sid = s2.sid and c.cid=#{cid}
</select>
<!-- 使用resultMap映射实体类和字段之间的一一对应关系 -->
<resultMap type="com.domain.Course" id="CourseResultMap">
<id property="id" column="cid"/>
<result property="name" column="cname"/>
<association property="teacher" javaType="com.domain.Teacher">
<id property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
<collection property="list" ofType="com.domain.Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<result property="sage" column="sage"/>
<result property="ssex" column="ssex"/>
</collection>
</resultMap>
<!--
方式二:
SELECT * FROM ksl_course WHERE cid=1;
SELECT * FROM ksl_teacher WHERE tid=1 //1 是上一个查询得到的tid的值
-->
<select id="getCourse2" parameterType="int" resultMap="CourseResultMap2">
select * from ksl_course c where cid=#{cid}
</select>
<!-- 使用resultMap映射实体类和字段之间的一一对应关系 -->
<resultMap type="com.domain.Course" id="CourseResultMap2">
<id property="id" column="cid"/>
<result property="name" column="cname"/>
<association property="teacher" column="tid" select="getTeacher"/>
<collection property="list" ofType="com.domain.Student" column="sid" select="getStudent"/>
</resultMap>
<select id="getTeacher" parameterType="int" resultType="com.domain.Teacher">
SELECT tid id, tname name FROM ksl_teacher WHERE tid=#{tid}
</select>
<select id="getStudent" parameterType="int" resultType="com.domain.Student">
SELECT s1.sid sid, s1.sname sname, s1.sage sage, s1.ssex ssex FROM ksl_student s1, ksl_score s2, ksl_course c WHERE s1.sid=s2.sid and s2.cid=c.cid and c.tid=#{tid}
</select>
</mapper>
3.在conf.xml中注册courseMapper.xml:
<mapper resource="com/mapping/courseMapper.xml"/>
4.association标签
MyBatis中使用association标签来解决一对一关联查询,association标签可使用如下属性:
property:对象属性的名称
javaType:对象属性的类型
column:所对应的外键字段名称
select:使用另一个查询封装的结果
4.collection标签
MyBatis中使用collection标签来解决一对多关联查询,ofType属性指定集合中元素的对象类型。
标签:odi 外键 bsp select 映射 bat encoding 联表查询 查询
原文地址:https://www.cnblogs.com/yuanfei1110111/p/10350699.html