文章目录[隐藏]
目的: 记录数据库表与实体对象之间不同的映射关系如何用mybatis的自定义sql和结果返回集处理。
1、三种对象映射关系
1.1 一对一
一个人对应一个身份证,一位同学对应一个班级,每个房间都有自己的房间号,当一个事物它对应另一个事物是唯一的,那么它们之间的关系就是一对一的。
这里我演示的案例是,一个学生有着一位老师
老师基础信息:
学生详细信息:
如果说,我们需要将两个表一起查出来,我们可以这么做:
问题: 如果对象的列重复了,必须要使用到别名
1、先定义实体结构,也就是我们返结果的实体类
public class Student { @TableId private int id; private String name; private int tid; @TableField(exist = false) private Teacher teacher; }
Teacher:
public class Teacher { @TableId private int id; private String name; }
2、 编写xml文件
这里有两种方式,使用association时的关键在于告诉mybatis如何加载关联(assocition)。
- 嵌套查询:通过执行另外一个 SQL 映射语句来返回预期的复杂类型。
- 嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集。
第一种: 使用嵌套查询,也就是使用另一个sql
// teacherMapper.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="com.lll.mybatisplusdemo.mapper.TeacherMapper"> <select id="getTeacher" parameterType="int" resultType="teacher"> select * from teacher where id = #{id}; </select> </mapper> // studentMapper.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"> <select id="getStudent2" parameterType="int" resultMap="getStudentMap2"> select * from student where id =#{id}; </select> <resultMap id="getStudentMap2" type="student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <result column="tid" property="tid"></result> <association property="teacher" javaType="Teacher" column="tid" select="com.lll.mybatisplusdemo.mapper.TeacherMapper.getTea<a style="color:transparent">本文来源gao($daima.com搞@代@#码(网5</a>cher"> <id column="id" property="id"></id> <result column="name" property="name"></result> </association> </resultMap> </mapper>
嵌套查询的方式很简单,但是对于大型数据集合和列表将不会表现很好。问题就是我们熟知的
“N+1 查询问题”。概括地讲, N+1 查询问题可以是这样引起的:
- 你执行了一个单独的 SQL 语句来获取结果列表(就是“+1”)。
- 对返回的每条记录,你执行了一个查询语句来为每个加载细节(就是“N”)。
第二种: 使用嵌套结果来映射联合查询来的数据
<?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="com.lll.mybatisplusdemo.mapper.StudentMapper"> <select id="getStudent" parameterType="int" resultMap="getStudentMap"> SELECT a.*,b.id as cid,b.name as cname FROM `student` as a,teacher as b WHERE a.id =#{id} and a.tid = b.id; </select> <resultMap id="getStudentMap" type="student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <result column="tid" property="tid"></result> <association property="teacher" javaType="Teacher"> <id column="cid" property="id"></id> <result column="cname" property="name"></result> </association> </resultMap> </mapper>