MyBatis从入门到精通笔记(5)高级映射


经常在一对一、一对多关系的场景下使用.
当然上面的需求,也可以通过多次查询获取。如果是中小型应用还是用高级映射比较方便, 但对于分库分表的应用,可能多次查询效率更高

一 一对一映射

1.1 嵌套结果映射。

使用自动映射处理一对一关系,通过别名让MyBatis 自动将值匹配到对应的字段上。

SysUser类添加一个角色的字段(用来一对一

	private SysRole role;

接口方法

    /**
     * 根据用户 id 获取用户信息和用户的角色信息
     *
     * @param id
     * @return
     */
    SysUser selectUserAndRoleById(Long id);

映射文件

    <!--别名需要使用嵌套字段-->
    <select id="selectUserAndRoleById" resultType="zyc.mybatis.simple.model.SysUser">
        select
            u.id,
            u.user_name userName,
            u.user_password userPassword,
            u.user_email userEmail,
            u.user_info userInfo,
            u.head_img headImg,
            u.create_time createTime,
            r.id "role.id",
            r.role_name "role.roleName",
            r.enabled "role.enabled",
            r.create_by "role.createBy",
            r.create_time "role.createTime"
        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
        where u.id = #{id}
    </select>

优点:只查询一次
缺点:无法懒加载,sql比较复杂

1.2 resultMap 支持映射继承

MyBatis 是支持resultMap 映射继承的,大多数情况下,我们都会用MBG生成代码。这时我们可以在我们自定义的映射文件中引用生成的部分代码片段。这时id需要加上命名空间

1.3 使用resultMap 的association 标签配置一对一映射

使用1.2节中的技术

先在RoleMapper.xml中添加一个resultMap

    <resultMap id="roleMap" type="zyc.mybatis.simple.model.SysRole">
        <id property="id" column="id"/>
        <result property="roleName" column="role_name"/>
        <result property="enabled" column="enabled"/>
        <result property="createBy" column= "create_by" />
        <result property="createTime" column="create_time " jdbcType="TIMESTAMP"/>
    </resultMap>

在UserMapper.xml中添加resultMap

        <resultMap id="userRoleMap" extends="userMap" type="zyc.mybatis.simple.model.SysUser">
            <association property="role" columnPrefix="role_" resultMap="zyc.mybatis.simple.mapper.RoleMapper.roleMap"/>
        </resultMap>

在UserMapper.xml中使用resultMap
注意所有角色的别名都有前缀role_

    <select id="selectUserAndRoleById2" resultMap="userRoleMap">
        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
        where u.id = #{id}
    </select>

1.4 association 标签的嵌套查询

嵌套查询时的常用属性

  • select :另一个映射查询的id, MyBatis 会额外执行这个查询获取嵌套对象的结果。
  • column :列名(或别名),将主查询中列的结果作为嵌套查询的参数,配置方式如column={propl=coll , prop2=col2}, prop1和prop2 将作为嵌套查询的参数。
  • fetchType :数据加载方式,可选值为lazy和eager ,分别为延迟加载和积极加载,这个配置会覆盖全局的lazyLoadingEnabled配置。

RoleMapper.xml添加查询

    <select id="selectRoleById" resultMap="roleMap">
        select * from sys_role where id = #{id}
    </select>

UserMapper.xml新增

        <resultMap id="userRoleMapSelect" extends="userMap" type="zyc.mybatis.simple.model.SysUser">
            <association property="role"
                         fetchType="lazy"
                         select="zyc.mybatis.simple.mapper.RoleMapper.selectRoleById"
                         column="{id=role_id}"/>
        </resultMap>	

    <select id="selectUserAndRoleByIdSelect" resultMap="userRoleMapSelect">
        select
            u.id,
            u.user_name,
            u.user_password,
            u.user_email,
            u.user_info,
            u.head_img,
            u.create_time,
            ur.role_id
        from sys_user u
                 inner join sys_user_role ur on u.id = ur.user_id
        where u.id = #{id}
    </select>

上面我们配置了fetchType="lazy",想要懒加载。但是测试结果发现懒加载无效。

mybatis-config.xml中增加以下配置即可

    <settings>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

1.5 lazyLoadTriggerMethods 参数

当aggressiveLazyLoading=false时,set该字段,不会触发查询。但get会。我们需要注意还有一些场景也会触发懒加载的查询
这个参数的含义是,当调用配置中的方法时,加载全部的延迟加载数据。默认值为equals , clone ,hashCode ,toString 。

二 一对多映射

一对一映射可以通过association标签来实现(也可以不用),一对多只能用collection标签来实现

2.1 单层嵌套映射

在SysRole类中,添加一个权限集合属性

    /**
     * 角色包含的权限列表
     */
    List<SysPrivilege> privilegeList;

在PrivilegeMapper.xml中添加一个ResultMap.注意column都有privilege_前缀

    <resultMap id="privilegeMap" type="zyc.mybatis.simple.model.SysPrivilege">
        <id property="id" column="id"/>
        <result property="privilegeName" column="privilege_name"/>
        <result property="privilegeUrl" column="privilege_url"/>
    </resultMap>

在中也添加一个ResultMap,这里用到了前面写的privilegeMap,是用collection标签关联的

    <resultMap id="rolePrivilegeListMap" extends="roleMap" type="zyc.mybatis.simple.model.SysRole">
        <collection property="privilegeList" columnPrefix="privilege_"
                    resultMap="zyc.mybatis.simple.mapper.PrivilegeMapper.privilegeMap"/>
    </resultMap>

在RoleMapper.xml中添加一个查询方法,查出所有的用户以及对应的权限

    <select id="selectAllRoleAndPrivileges" resultMap="rolePrivilegeListMap">
        select
            r.id,
            r.role_name,
            r.enabled,
            r.create_by,
            r.create_time,
            p.id privilege_id,
            p.privilege_name privilege_privilege_name,
            p.privilege_url privilege_privilege_url
        from sys_role r
                 inner join sys_role_privilege rp on rp.role_id = r.id
                 inner join sys_privilege p on p.id = rp.privilege_id
    </select>

2.2 多层嵌套映射

下面的例子是双层的,但同理可写出更多层的

用户类增加角色集合

	/**
	 * 用户的角色集合
	 */
	private List<SysRole> roleList;

UserMapper.xml中增加一个ResultMap,这里用到了2.1中的内容

        <resultMap id="userRoleListMap" extends="userMap" type="zyc.mybatis.simple.model.SysUser">
            <collection property="roleList" columnPrefix="role_"
                        resultMap="zyc.mybatis.simple.mapper.RoleMapper.rolePrivilegeListMap"/>
        </resultMap>

编写一个查询语句,因为映射时需要区分列(使用columnPrefix属性)。所以这里的部分别名会很长

    <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,
            p.id role_privilege_id,
            p.privilege_name role_privilege_privilege_name,
            p.privilege_url role_privilege_privilege_url
        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
                 inner join sys_role_privilege rp on rp.role_id = r.id
                 inner join sys_privilege p on p.id = rp.privilege_id
    </select>

2.3 id标签的作用

在ResultMap中有个id标签,它的作用主要就是去重。

  • 当我们使用集合字段时,MyBatis会对里面的对象去重。去重逻辑就是:1.有id标识的,判断id属性是否相等 2.没有id的则判断每个属性是否相同(效率低下
  • 相同的保留第一个结果
  • 当对象有嵌套属性时,嵌套属性也有去重判断。比如顶层对象的属性都相同,MyBatis还会继续比较嵌套属性是否都相同(有种递归的感觉)。

2.4 嵌套查询

映射的缺点就是一次性查出,不能懒加载。
下面我们使用嵌套查询

在PrivilegeMapper.xml中添加select标签

    <select id="selectPrivilegeByRoleId" resultMap="privilegeMap">
        select p.*
        from sys_privilege p
                 inner join sys_role_privilege rp on rp.privilege_id = p.id
        where role_id = #{roleId}
    </select>

在RoleMapper.xml中添加

    <resultMap id="rolePrivilegeListMapSelect" extends="roleMap" type="zyc.mybatis.simple.model.SysRole">
        <collection property="privilegeList"
                    fetchType="lazy"
                    select="zyc.mybatis.simple.mapper.PrivilegeMapper.selectPrivilegeByRoleId"
                    column="{roleId=id}"/>
    </resultMap>

    <select id="selectRoleByUserId" resultMap="rolePrivilegeListMapSelect">
        select
            r.id,
            r.role_name,
            r.enabled,
            r.create_by,
            r.create_time
        from sys_role r
                 inner join sys_user_role ur on ur.role_id = r.id
        where ur.user_id = #{userId}
    </select>

在UserMapper.xml中添加

        <resultMap id="userRoleListMapSelect" extends="userMap" type="zyc.mybatis.simple.model.SysUser">
            <collection property="roleList"
                        fetchType="lazy"
                        select="zyc.mybatis.simple.mapper.RoleMapper.selectRoleByUserId"
                        column="{userId=id}"/>
        </resultMap>

    <select id="selectAllUserAndRolesSelect" resultMap="userRoleListMapSelect">
        select
            u.id,
            u.user_name,
            u.user_password,
            u.user_email,
            u.user_info,
            u.head_img,
            u.create_time
        from sys_user u
        where u.id = #{id}
    </select>

三 鉴别器映射

有时我们可能会根据部分字段来决定映射的类型。

discriminator 标签常用的两个属性如下。

  • column :该属性用于设置要进行鉴别比较值的列。
  • javaType :该属性用于指定列的类型,保证使用相同的Java 类型来比较值。

discriminator 标签可以有1个或多个case 标签,case 标签包含以下三个属性。

  • value :该值为discriminator 指定column 用来匹配的值。
  • resultMap :当column 的值和value 的值匹配时,可以配置使用resultMap 指定的映射,resultMap 优先级高于resultType
  • resultType :当column 的值和value 的值匹配时,用于配置使用resultType指定的映射。
  • case 标签下面可以包含的标签和resultMap 一样,用法也一样(就是id,result等标签)

用法示例
RoleMapper.xml中添加



    <select id="selectRoleByUserIdChoose" resultMap="rolePrivilegeListMapChoose">
        select
            r.id,
            r.role_name,
            r.enabled,
            r.create_by,
            r.create_time
        from sys_role r
                 inner join sys_user_role ur on ur.role_id = r.id
        where ur.user_id = #{userId}
    </select>

    <resultMap id="rolePrivilegeListMapChoose" type="zyc.mybatis.simple.model.SysRole">
        <discriminator column="enabled" javaType="int">
            <case value="1" resultMap="rolePrivilegeListMapSelect"/>
            <case value="0" resultMap="roleMap"/>
        </discriminator>
    </resultMap>

注意这里的rolePrivilegeListMapSelect这个ResultMap是会嵌套查询的。而roleMap这个不会

四 使用存储过程

略。。如果需要了解,具体参考原文

五 使用枚举字段

5.1 使用MyBatis提供的枚举处理器

为了方便校验,我们可以将实体类的字段设为枚举类型。MyBtais也提供了两种处理器,

  • 默认的EnumTypeHandler(处理字符串到枚举的转换,默认就是枚举名
  • EnumOrdinalTypeHandler(处理枚举的ordinal到枚举的转换),默认不开启,需要在mybatis-config .xml 中添加配置。

添加枚举

public enum Enabled {
	disabled,//禁用
	enabled,;//启用

}

mybatis-config .xml

    <typeHandlers>
        <typeHandler
                javaType="zyc.mybatis.simple.type.Enabled"
                handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
    </typeHandlers>

5.2 自定义类型处理器

public class EnabledTypeHandler implements TypeHandler<Enabled> {
	private final Map<Integer, Enabled> enabledMap = new HashMap<Integer, Enabled>();

	public EnabledTypeHandler() {
		for(Enabled enabled : Enabled.values()){
			enabledMap.put(enabled.getValue(), enabled);
		}
	}
	
	public EnabledTypeHandler(Class<?> type) {
		this();
	}

	@Override
	public void setParameter(PreparedStatement ps, int i, Enabled parameter, JdbcType jdbcType) throws SQLException {
		ps.setInt(i, parameter.getValue());
	}

	@Override
	public Enabled getResult(ResultSet rs, String columnName) throws SQLException {
		Integer value = rs.getInt(columnName);
		return enabledMap.get(value);
	}

	@Override
	public Enabled getResult(ResultSet rs, int columnIndex) throws SQLException {
		Integer value = rs.getInt(columnIndex);
		return enabledMap.get(value);
	}

	@Override
	public Enabled getResult(CallableStatement cs, int columnIndex) throws SQLException {
		Integer value = cs.getInt(columnIndex);
		return enabledMap.get(value);
	}

}

也要在mybatis-config .xml配置文件中设置

上面继承的是TypeHandler,需要注意BaseTypeHandler这个类。MyBatis 会对继承了TypeReference<T >的类进行特殊处理,获取这里指定的泛型类型作为javaType 属性,因此在配置的时候就不需要指定javaType 了

参考

  1. 《MyBatis 从入门到精通》
  2. 源码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值