1、高级结果映射
1一对一映射
1.1.1 使用resultMap配置一对一映射
association标签的映射查询常用的属性如下。
property: 对应实体类中的属性名,必填项。
javaType:属性对应的Java类型。
resultMap:可以直接使用现有的resultMap,而不需要在这里配置。
columnPrefix:查询列的前缀,配置前缀后,在子标签配置result的column时可以省略前缀。
association直接映射
<resultMap id="userRoleMap" extends="userMap" type="tk.mybatis.simple.model.SysUser"> <association property="role" columnPrefix="role_" resultMap="tk.mybatis.simple.mapper.RoleMapper.roleMap"/> </resultMap>
<resultMap id="roleMap" type="tk.mybatis.simple.model.SysRole"> <id property="id" column="id"/> <result property="roleName" column="role_name" javaType="String" /> <result property="enabled" column="enabled"/> </resultMap>
<select id="selectAllUserAndRoles" resultMap="userRoleListMap"> select u.id, u.user_name, u.user_password, u.user_email, u.user_info, u.head_img, u.create_time, r.id role_id, r.role_name role_role_name, r.enabled role_enabled, r.create_by role_create_by, r.create_time role_create_time from sys_user u inner join sys_user_role ur on u.id = ur.user_id inner join sys_role r on ur.role_id = r.id </select>
association标签的嵌套查询
association标签的嵌套查询常用的属性如下。
select : 另一个映射查询的id,mybatis会额外执行这个查询获取嵌套对象的结果。
column:列名(或别名)、将主查询中列的结果作为嵌套查询的参数。配置方式如column={prop1=col1,prop2=col2},prop1和prop2将作为嵌套查询的参数。
fetchType:数据加载方式,可选值为lazy和eager,分别为延迟加载和积极加载,这个配置会覆盖全局的lazyLoadingEnabled配置。
<resultMap id="userRoleMapSelect" extends="userMap" type="tk.mybatis.simple.model.SysUser"> <association property="role" fetchType="lazy" select="tk.mybatis.simple.mapper.RoleMapper.selectRoleById" column="{id=role_id}"/> </resultMap>