Mybatis中ResultMap常用参数详解
ResultMap常用标签
以下例子以Office对象为例
public class Office {
private String id;
private String name;
private String sort;
private String code;
private String type;
private User createBy;
private Office parent;
private List<OfficeReceiver> receiverList;
}
ID
id标签一般设置为一条记录的主键ID
column: sql的字段名
property: 需要映射的对象属性名
需要注意的是: 如果resultMap中设置了id标签,并且查询结果集中存在相同id的数据,
那么,mybatis会自动去重只保留一条
<id column="id" property="id"/>
如果想要避免自动去重,可以根据业务需要多设置一个id标签,如:
/** 两条完全一致的数据无法避免自动去重,应当选择其他返回方式,如Map等 */
<id column="id" property="id"/>
<id column="name" property="name"/>
result
普通参数标签
column: sql的字段名
property: 需要映射的对象属性名
<result column="id" property="id"/>
association
对象标签(一对一)
用法与ResultMap基本一致,下图中parent.name会自动映射到Office对象中parent子对象的name属性中
property: 需要映射的属性名
javaType: 返回的java类型
<association property="parent" javaType="Office">
<id property="id" column="parent.id"/>
<result property="name" column="parent.name"/>
</association>
collection
对象标签(一对多)
property: 映射的属性名
javaType: 返回的java类型,collection中一般为List
ofType: 该查询返回的java实体类型
column: 非必填,执行这个子查询时传入的参数,多个参数","分隔,
如:column=“officeId=id,officeName=name” 左边为子查询需要传入的参数名,右侧为本条查询的sql字段名(有别名则为别名)
select: 执行的查询所在路径及id
fetchType: 懒加载模式
<collection property="receiverList" javaType="ArrayList" ofType="com.sys.entity.OfficeReceiver" column="officeId=id" select="com.sys.dao.OfficeReceiverDao.getReceiverById" fetchType="lazy"/>
resultMap的继承
关键字:extends: 需要继承的resultMap的id
应用场景:一个resultMap定义公共的字段参数,再根据的业务需要分别拼接不同的字段参数或子查询等.减少重复代码
<resultMap id="findByIdResult" type="Office" extends="officeResult">
<collection property="receiverList" javaType="ArrayList" ofType="com.sys.entity.OfficeReceiver" column="officeId=id" select="com.sys.dao.OfficeReceiverDao.getReceiverById" fetchType="lazy"/>
</resultMap>
以下为文中所用到的示例:
OfficeDao.xml
<resultMap id="officeResult" type="Office">
<id column="id" property="id"/>
<result column="code" property="code"/>
<result column="name" property="name"/>
<result column="sort" property="sort"/>
<result column="type" property="type"/>
<association property="createBy" javaType="User">
<id property="id" column="createBy.id"/>
</association>
<association property="parent" javaType="Office">
<id property="id" column="parent.id"/>
<result property="name" column="parent.name"/>
</association>
</resultMap>
<resultMap id="findByIdResult" type="Office" extends="officeResult">
<collection property="receiverList" javaType="ArrayList" ofType="com.sys.entity.OfficeReceiver" column="officeId=id" select="com.sys.dao.OfficeReceiverDao.getReceiverById" fetchType="lazy"/>
</resultMap>
<select id="findById" resultMap="findByIdResult">
SELECT a.* FROM office a
where a.office_id = #{officeId}
</select>
OfficeReceiverDao.xml
<select id="getReceiverById" resultType="OfficeReceiver">
SELECT
a.*
FROM office_receiver a
where
a.office_id = #{officeId}
</select>
本文详细介绍了MyBatis中ResultMap的使用方法及其常用参数,包括ID、result、association、collection等标签的配置与应用实例。通过具体示例说明了如何实现对象间的一对一、一对多关联。
393

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



