MyBatis一对一关联查询
在 MyBatis 中,通过 <resultMap> 元素的子元素 <association> 处理一对一级联关系。示例代码如下。
<association property="studentCard" column="cardId" javaType="net.biancheng.po.StudentCard" select="net.biancheng.mapper.StudentCardMapper.selectStuCardById" />在 <association> 元素中通常使用以下属性。
- property:指定映射到实体类的对象属性。
- column:指定表中对应的字段(即查询返回的列名)。
- javaType:指定映射到实体对象属性的类型。
- select:指定引入嵌套查询的子 SQL 语句,该属性用于关联映射中的嵌套查询。
一对一关联查询可采用以下两种方式:
- 单步查询,通过关联查询实现
- 分步查询,通过两次或多次查询,为一对一关系的实体 Bean 赋值
示例
下面以学生和学号为例讲解一对一关联查询的处理过程。1)创建数据表
创建 student(学生)和 studentcard(学号)数据表,SQL 语句如下。CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `sex` tinyint(4) DEFAULT NULL, `cardId` int(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `cardId` (`cardId`), CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cardId`) REFERENCES `studentcard` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; insert into `student`(`id`,`name`,`sex`,`cardId`) values (1,'C语言中文网',0,1),(2,'编程帮',0,2),(3,'赵小红',1,3),(4,'李晓明',0,4),(5,'李紫薇',1,5),(6,'钱百百',0,NULL); DROP TABLE IF EXISTS `studentcard`; CREATE TABLE `studentcard` ( `id` int(20) NOT NULL AUTO_INCREMENT, `studentId` int(20) DEFAULT NULL, `startDate` date DEFAULT NULL, `endDate` date DEFAULT NULL, PRIMARY KEY (`id`), KEY `studentId` (`studentId`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; insert into `studentcard`(`id`,`studentId`,`startDate`,`endDate`) values (1,20200311,'2021-03-01','2021-03-11'),(2,20200314,'2021-03-01','2021-03-11'),(3,20200709,'2021-03-01','2021-03-11'),(4,20200508,'2021-03-01','2021-03-11'),(5,20207820,'2021-03-01','2021-03-11');
2)创建持久化类
在 myBatisDemo 应用的 net.biancheng.po 包下创建数据表对应的持久化类 Student 和 StudentCard。Student 的代码如下:
package net.biancheng.po; public class Student { private int id; private String name; private int sex; private StudentCard studentCard; /*省略setter和getter方法*/ @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", studentCard=" + studentCard + "]"; } }StudentCard 的代码如下:
package net.biancheng.po; import java.util.Date; public class StudentCard { private int id; private int studentId; private Date startDate; private Date endDate; /*省略setter和getter方法*/ @Override public String toString() { return "StudentCard [id=" + id + ", studentId=" + studentId + "]"; } }
分步查询
新建 StudentCardMapper 类,代码如下。package net.biancheng.mapper; import net.biancheng.po.StudentCard; public interface StudentCardMapper { public StudentCard selectStuCardById(int id); }StudentCardMapper.xml 对应映射 SQL 语句代码如下。
<mapper namespace="net.biancheng.mapper.StudentCardMapper"> <select id="selectStuCardById" resultType="net.biancheng.po.StudentCard"> SELECT * FROM studentCard WHERE id = #{id} </select> </mapper>StudentMapper 类方法代码如下。
package net.biancheng.mapper; import net.biancheng.po.Student; public interface StudentMapper { public Student selectStuById1(int id); public Student selectStuById2(int id); }StudentMapper.xml 代码如下。
<mapper namespace="net.biancheng.mapper.StudentMapper"> <!-- 一对一根据id查询学生信息:级联查询的第一种方法(嵌套查询,执行两个SQL语句) --> <resultMap type="net.biancheng.po.Student" id="cardAndStu1"> <id property="id" column="id" /> <result property="name" column="name" /> <result property="sex" column="sex" /> <!-- 一对一级联查询 --> <association property="studentCard" column="cardId" javaType="net.biancheng.po.StudentCard" select="net.biancheng.mapper.StudentCardMapper.selectStuCardById" /> </resultMap> <select id="selectStuById1" parameterType="Integer" resultMap="cardAndStu1"> select * from student where id=#{id} </select> </mapper>测试代码如下。
public class Test { public static void main(String[] args) throws IOException { InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config); SqlSession ss = ssf.openSession(); Student stu = ss.getMapper(StudentMapper.class).selectStuById1(2); System.out.println(stu); } }运行结果如下。
DEBUG [main] - ==> Preparing: select * from student where id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - ====> Preparing: SELECT * FROM studentCard WHERE id = ?
DEBUG [main] - ====> Parameters: 2(Integer)
DEBUG [main] - <==== Total: 1
DEBUG [main] - <== Total: 1
Student [id=2, name=编程帮, sex=0, studentCard=StudentCard [id=2, studentId=20200314]]
单步查询
在 StudentMapper.xml 中添加以下代码。<resultMap type="net.biancheng.po.Student" id="cardAndStu2"> <id property="id" column="id" /> <result property="name" column="name" /> <result property="sex" column="sex" /> <!-- 一对一级联查询 --> <association property="studentCard" javaType="net.biancheng.po.StudentCard"> <id property="id" column="id" /> <result property="studentId" column="studentId" /> </association> </resultMap> <select id="selectStuById2" parameterType="Integer" resultMap="cardAndStu2"> SELECT s.*,sc.studentId FROM student s,studentCard sc WHERE s.cardId = sc.id AND s.id=#{id} </select>在 StudentMapper 中添加以下方法。
public Student selectStuById2(int id);运行结果如下。
DEBUG [main] - ==> Preparing: SELECT s.*,sc.studentId FROM student s,studentCard sc WHERE s.cardId = sc.id AND s.id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <== Total: 1
Student [id=2, name=编程帮, sex=0, studentCard=StudentCard [id=2, studentId=20200314]]