MyBatis Mapper 文件解析:一对一关联查询示例
这段代码是一个 MyBatis 的 mapper 文件,其中定义了一个 namespace 为 com.ape.mapper.StudentMapper 的映射器。在该映射器中,定义了一个 resultMap,命名为 Student_Class_Map,用于将查询结果映射到 Student 类中。
resultMap 中使用了 association 标签,表示 Student 类中的 bj 属性是一个关联对象,需要进行关联查询,并将查询结果映射到 bj 对象中。
同时,该 mapper 文件中还定义了一个 select 语句,id 为 findAllStudent,用于查询所有的学生信息以及对应的班级信息,并将结果映射到 Student 类中。
代码解析:
<?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.ape.mapper.StudentMapper'>
<!-- 手动映射
column:数据表的字段名
property:java中实体类的属性
-->
<resultMap type='Student' id='Student_Class_Map'>
<result column='sid' property='sid'/>
<result column='sname' property='sname'/>
<result column='birthday' property='birthday'/>
<result column='ssex' property='ssex'/>
<result column='classid' property='classid'/>
<association property='bj'>
<result column='classid' property='classid'/>
<result column='classname' property='classname'/>
</association>
</resultMap>
<!--一对一查询-->
<select id='findAllStudent' resultMap='Student_Class_Map'>
select * from student
inner join class on student.classid=class.classid
</select>
</mapper>
代码说明:
resultMap标签定义了结果映射关系,type属性指定映射到的 Java 类,id属性是 resultMap 的唯一标识。result标签将数据库表字段映射到 Java 类属性。association标签表示关联关系,property属性指定 Java 类中的关联属性,column属性指定数据库表中关联字段。select标签定义查询语句,id属性是查询语句的唯一标识,resultMap属性指定结果映射关系。
通过使用 association 标签,MyBatis 可以将 student 表和 class 表中的相关数据映射到 Student 类和 bj 对象中,实现了一对一的关联查询。
原文地址: https://www.cveoy.top/t/topic/mht8 著作权归作者所有。请勿转载和采集!