Skip to content
生如风生如风
主页
github icon
  • Mybatis的查询

    Mybatis—鉴别映射器

    author icon生如风calendar icon2022年4月12日category icon
    • Mybatis
    tag icon
    • Mybatis
    timer icon大约 1 分钟

    此页内容
    • Mybatis的查询

    学习记录mybatis鉴别映射器

    discriminator可以根据不同结果信息,执行不同的查询操作

    # Mybatis的查询

    数据表:用户表user 角色表role 中间表user_role

    描述:查询用户及其对应的角色信息,如果用户信息的enable为1,则查询出相应的角色信息;如果用户信息enable为0,则不需要查询角色信息。

    1. xml:
    <mapper namespace="com.liwang.mybatis02.mapper.UserMapper">  
    
        <!--基础User信息-->
        <resultMap id="BaseUserMap" type="com.liwang.mybatis02.model.User">
            <id property="id" column="id"/>
            <result property="username" column="username"/>
            <result property="email" column="email"/>
            <result property="enable" column="enable"/>
        </resultMap>
    
        <!--User联表Role信息-->
        <resultMap id="UserMapWithRole" type="com.liwang.mybatis02.model.User" extends="BaseUserMap">
            <collection property="roles" ofType="com.liwang.mybatis02.model.Role" columnPrefix="role_"
                        resultMap="com.liwang.mybatis02.mapper.RoleMapper.BaseRoleMap">
            </collection>
        </resultMap>
    
        <!--使用鉴别器discriminator 判断是否需要包含Role信息-->
        <resultMap id="UserMapWithRole2" type="com.liwang.mybatis02.model.User">
            <discriminator javaType="int" column="enable">
                <case value="1" resultMap="UserMapWithRole"></case>
                <case value="0" resultMap="BaseUserMap"></case>
            </discriminator>
        </resultMap>
    
        <!--查询语句-->
        <select id="getUserWithRole2" resultMap="UserMapWithRole2">
            select u.*,r.id as role_id,r.name as role_name
            from user as u
            left join user_role ur on u.id = ur.uid
            left join role r on ur.rid = r.id;
        </select>
    
    </mapper>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    1. mapper:
    public interface UserMapper {
        // 获取用户信息及角色信息
        List<User> getUserWithRole2();
    }
    
    1
    2
    3
    4
    1. test
    @Test
    public void getUserWithRole() {
        List<User> users = userMapper.getUserWithRole2();
            for (User user : users) {
                System.out.println("user = " + user);
            }
    }
    
    1
    2
    3
    4
    5
    6
    7
    1. 结果

    可以看看我的学习——基于Hexo的个人博客: 网站:https://liwangc.gitee.io/open in new window

    —————————————————————————

    作为初学者,很多知识都没有掌握,见谅,如有错误请指出,以期进步,感谢!。后续有新的学习,继续补充上来。

    默认页脚
    Copyright © 2026 生如风