一对一和一对多
一对一
<?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.mahe666.mapper.StudentMapper">
<!--
思路
1,查询所有的学生
2,根据查询出来的学生的tid,寻找对应的老师
因为resultType查不出来想要的teacher
所以给这个返回的东西做点手脚,给它变为resultMap
-->
<select id="getStudent" resultMap="StudentAndTeacherMap">
select * from student
</select>
<resultMap id="StudentAndTeacherMap" type="student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性我们需要单独处理-->
<!--
如果是个对象,我们需要使用association
如果是个集合,我们需要使用collection
<association property=""/>
<collection property=""/>
-->
<!--property是返回类型的属性,javaType是对应的实体类-->
<association property="teacher" column="tid" javaType="teacher" select="getTeacherByTid"/>
</resultMap>
<select id="getTeacherByTid" resultType="teacher">
select * from teacher where id = #{tid}
</select>
</mapper>
一对多
<?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.mahe666.mapper.TeacherMapper">
<!--子查询的方式-->
<select id="getTeacher2" resultMap="teacherAndStudentMap2">
select * from teacher
</select>
<resultMap id="teacherAndStudentMap2" type="teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="studentList" column="id" javaType="ArrayList" ofType="student" select="getStudentByTid"/>
</resultMap>
<select id="getStudentByTid" resultType="student">
select * from student where tid =#{id}
</select>
</mapper>
多参数传递
column="{参数名1 = 列名1},{参数名2 = 列名2}"
相关博客:https://blog.csdn.net/qq_36008278/article/details/116158469