mybatis association的两种形式

本文介绍MyBatis中使用嵌套resultMap和嵌套select语句进行复杂对象映射的方法。通过示例展示了如何将数据库查询结果映射到Java对象,包括基本属性映射及关联对象的嵌套映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、嵌套的resultMap
<?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="org.zsm.myBatis.day02.inner.IStudentOperation">
<!-- 定义java Bean的属性与数据库的列之间的映射 -->
<resultMap type="Teacher" id="teacherResultMap">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
<result property="gender" column="t_gender"/>
<result property="researchArea" column="research_area"/>
</resultMap>
<resultMap type="Student" id="studentResultMap">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="gender" property="gender" />
<result column="major" property="major" />
<result column="grade" property="grade"/>
<!-- 引用teacherResultMap -->
<association property="supervisor" resultMap="teacherResultMap"/>
</resultMap>

<!-- SQL语句中以"#{}"的形式引用参数 -->
<select id="getById" parameterType="int" resultMap="studentResultMap">
SELECT st.id,st.name,st.gender,st.major,st.grade,t.id t_id,t.name t_name,
     t.gender t_gender,t.research_area 
FROM student st, teacher t
WHERE st.supervisor_id = t.id AND st.id=#{id}
</select>
</mapper>


二、嵌套的select语句
<?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="org.zsm.myBatis.day02.inner.IStudentOperation">
<!-- 定义java Bean的属性与数据库的列之间的映射 -->
<resultMap type="Teacher" id="supervisorResultMap">  
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
<result property="gender" column="t_gender"/>
<result property="researchArea" column="research_area"/>
</resultMap>
<resultMap type="Student" id="studentResultMap">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="gender" property="gender" />
<result column="major" property="major" />
<result column="grade" property="grade"/>
<!-- 引用teacherResultMap -->
<association property="supervisor" column="supervisor_id" select="selectSupervisor"/>
</resultMap>
<!-- SQL语句中以"#{}"的形式引用参数 -->
<select id="getById" parameterType="int" resultMap="studentResultMap">
     select id,name,gender,major,grade,supervisor_id from student where id =#{id}
</select>
<select id="selectSupervisor" parameterType="int" resultMap="supervisorResultMap">
     select id,name,gender,research_area from teacher where id = #{id}
</select>
</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值