Mybatis 查询对象中嵌套其他对象的解决方法有两种,一种是用关联另一个resultMap的形式,如
<association property="office" javaType="Office" resultMap="officeMap"/>
<mapper namespace="com.dixn.oa.modules.sys.dao.RoleDao">
<resultMap type="Office" id="officeMap">
<id property="id" column="id" />
<result property="name" column="office.name" />
<result property="code" column="office.code" />
</resultMap>
<resultMap id="roleResult" type="Role">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="enname" column="enname" />
<result property="roleType" column="roleType" />
<result property="dataScope" column="dataScope" />
<result property="remarks" column="remarks" />
<result property="useable" column="useable" />
<association property="office" javaType="Office" resultMap="officeMap"/>
<collection property="menuList" ofType="Menu">
<id property="id" column="menuList.id" />
</collection>
<collection property="officeList" ofType="Office">
<id property="id" column="officeList.id" />
</collection>
</resultMap>
<sql id="roleColumns">
a.id,
a.office_id AS "office.id",
a.name,
a.enname,
a.role_type AS roleType,
a.data_scope AS dataScope,
a.remarks,
a.create_by AS "createBy.id",
a.create_date,
a.update_by AS "updateBy.id",
a.update_date,
a.del_flag,
o.name AS "office.name",
o.code AS "office.code",
a.useable AS useable,
a.is_sys AS sysData
</sql>
<select id="get" resultMap="roleResult">
SELECT
<include refid="roleColumns"/>
rm.menu_id AS "menuList.id",
ro.office_id AS "officeList.id"
FROM sys_role a
JOIN sys_office o ON o.id = a.office_id
LEFT JOIN sys_role_menu rm ON rm.role_id = a.id
LEFT JOIN sys_role_office ro ON ro.role_id = a.id
WHERE a.id = #{id}
</select>
另一种联合查询 (一对一)的实现,但是这种方式有“N+1”的问题,不建议使用
<resultMap id="roleResult" type="Role">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="enname" column="enname" />
<result property="roleType" column="roleType" />
<result property="dataScope" column="dataScope" />
<result property="remarks" column="remarks" />
<result property="useable" column="useable" />
<association property="office" javaType="Office" column="id" select="getOfficeById"/>
<collection property="menuList" ofType="Menu">
<id property="id" column="menuList.id" />
</collection>
<collection property="officeList" ofType="Office">
<id property="id" column="officeList.id" />
</collection>
</resultMap>
<select id="getOfficeById" resultType="Office"> select o.name AS "office.name",o.code AS "office.code" from sys_office o where o.id = #{id} </select> 以上就是两种对象内嵌套对象查询的实现。
本文介绍了MyBatis中处理对象嵌套对象的关联查询方法,包括使用resultMap的方式以及联合查询(一对一)的方式。尽管联合查询可能导致'N+1'问题,但在特定场景下仍具实用性。
556

被折叠的 条评论
为什么被折叠?



