MyBatis series (13): Use discriminator discriminator mapping

This blog mainly on the simple use of a discriminator mapping discriminator label.

1. clear demand

Early in the design, enabled field sys_role table has two possible values, where 1 is enabled, 0 for disabled, when the state had enabled the authority information corresponding to the state disabled when there is no corresponding rights information, simply check out the role information can be.

So we need to: query the user id list of roles owned by the user, if the role is enabled, it continues to check out the list of permissions corresponding to the role, if the role is disabled, you do not need to query the corresponding list of permissions.

2. implementation

First of all, we need to create a mapping table roleMapExtend role in SysRoleMapper.xml, pay attention to where we used before the new extension classes SysRoleExtend:

<resultMap id="roleMapExtend" type="com.zwwhnly.mybatisaction.model.SysRoleExtend">
    <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>

Then review under Part blog used to rolePrivilegeListMapSelect mapping, because you'll use:

<resultMap id="rolePrivilegeListMapSelect" extends="roleMap"
           type="com.zwwhnly.mybatisaction.model.SysRoleExtend">
    <collection property="sysPrivilegeList" fetchType="lazy"
                column="{roleId=id}"
                select="com.zwwhnly.mybatisaction.mapper.SysPrivilegeMapper.selectPrivilegeByRoleId"/>
</resultMap>

Next new hero of this blog and the corresponding mapping rolePrivilegeListMapChoose query:

<resultMap id="rolePrivilegeListMapChoose"
           type="com.zwwhnly.mybatisaction.model.SysRoleExtend">
    <discriminator column="enabled" javaType="int">
        <case value="1" resultMap="rolePrivilegeListMapSelect"/>
        <case value="0" resultMap="roleMapExtend"/>
    </discriminator>
</resultMap>
<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>

discriminator tag used to explain two attributes:

  • column: To set the column name that identifies the comparison value.
  • javaType: Specifies the type of the columns, using the same Java type ensure to compare values.

discriminator labels may have one or more case labels, case the label contains the following three properties:

  • value: This column label attribute value discriminator for matching values.
  • resultMap: when the value of the column and the value of the matching value, can be configured using the specified map resultMap, resultMap priority than resultType.
  • resultType: When the value of the column and the value of the match, for resultType configured to use the mapping specified.

The following case label may contain labels and resultMap as usage is the same.

And add the following methods SysRoleMapper interface:

/**
 * 根据用户id获取用户的角色信息
 *
 * @param userId
 * @return
 */
List<SysRoleExtend> selectRoleByUserIdChoose(Long userId);

3. Unit Testing

Add the following test method SysRoleMapperTest test class:

@Test
public void testSelectRoleByUserIdChoose() {
    SqlSession sqlSession = getSqlSession();

    try {
        SysRoleMapper sysRoleMapper = sqlSession.getMapper(SysRoleMapper.class);

        // 将id=2的角色的enabled赋值为0
        SysRole sysRole = sysRoleMapper.selectById(2L);
        sysRole.setEnabled(0);
        sysRoleMapper.updateById(sysRole);

        // 获取用户id为1的角色
        List<SysRoleExtend> sysRoleExtendList = sysRoleMapper.selectRoleByUserIdChoose(1L);
        for (SysRoleExtend item : sysRoleExtendList) {
            System.out.println("角色名:" + item.getRoleName());
            if (item.getId().equals(1L)) {
                // 第一个角色存在权限信息
                Assert.assertNotNull(item.getSysPrivilegeList());
            } else if (item.getId().equals(2L)) {
                // 第二个角色的权限为null
                Assert.assertNull(item.getSysPrivilegeList());
                continue;
            }
            for (SysPrivilege sysPrivilege : item.getSysPrivilegeList()) {
                System.out.println("权限名:" + sysPrivilege.getPrivilegeName());
            }
        }
    } finally {
        sqlSession.close();
    }
}

Run the test code, the test passes, outputting the log follows:

DEBUG [main] - ==> Preparing: SELECT id,role_name,enabled,create_by,create_time FROM sys_role WHERE id = ?

DEBUG [main] - ==> Parameters: 2(Long)

TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time

TRACE [main] - <== Row: 2, ordinary users, 1, 1, 2019-06-2718: 21: 12.0

DEBUG [main] - <== Total: 1

DEBUG [main] - ==> Preparing: UPDATE sys_role SET role_name = ?,enabled = ?,create_by=?, create_time=? WHERE id=?

DEBUG [main] - ==> Parameters: Ordinary users (String), 0 (Integer), 1 (Long), 2019-06-27 18: 21: 12.0 (Timestamp), 2 (Long)

DEBUG [main] - <== Updates: 1

DEBUG [main] - ==> Preparing: 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 = ?

DEBUG [main] - ==> Parameters: 1(Long)

TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time

TRACE [main] - <== Row: 1, the administrator, 1, 1, 2019-06-2718: 21: 12.0

TRACE [main] - <== Row: 2, the average user, 0, 1, 2019-06-2718: 21: 12.0

DEBUG [main] - <== Total: 2

Role name: Administrator

DEBUG [main] - ==> Preparing: SELECT p.* FROM sys_privilege p INNER JOIN sys_role_privilege rp ON rp.privilege_id = p.id WHERE rp.role_id = ?

DEBUG [main] - ==> Parameters: 1(Long)

TRACE [main] - <== Columns: id, privilege_name, privilege_url

TRACE [main] - <== Row: 1, user management, / users

TRACE [main] - <== Row: 2, role management, / roles

TRACE [main] - <== Row: 3, system log, / logs

DEBUG [main] - <== Total: 3

Permissions name: User Management

Permissions name: Role Management

Permissions Name: System Log

Role name: ordinary users

As can be seen from the log, the role of 1 is enabled, it is also the implementation of a query to get the list of roles permissions, roles 2 is disabled, so no execution.

4. The reference source and

Source Address: https://github.com/zwwhnly/mybatis-action.git , welcome to download.

Liuzeng Hui "MyBatis from entry to the master."

The original is not easy, if that article can learn something, like a welcome point, a commentary on, off a note, this is my greatest motivation insist on writing.

If you are interested, please add my micro letter: zwwhnly , waiting for you to talk technology, workplace, work and other topics (PS: I am a programmer struggle in Shanghai).

Published 34 original articles · won praise 107 · views 20000 +

Guess you like

Origin blog.csdn.net/zwwhnly/article/details/103851046