discriminator鉴别器的使用

本文介绍了一个实用的 myBatis 映射技巧,通过使用 Discriminator 标签来根据特定字段的不同值实现动态的 ResultMap 映射。示例展示了如何根据不同性别的值查询员工信息并选择性地加载部门编号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

myBatis可以使用discriminator判断某一列的值,然后根据某一列的值改变封装行为

ex:

根据性别字段进行判断,如果是女生,则查询对应的部门编号,如果是男生,则不用查

<resultMap id="MyEmpDis" type="com.test.beans.Employee">
        <id column="id" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="email" property="email"/>
        <result column="gender" property="gender"/>
        <!--column:指定判定的列名
	 		javaType:列值对应的java类型  -->
        <discriminator javaType="string" column="gender">
            <!--女生 resultType:指定封装的结果类型;不能缺少。/resultMap-->
            <case value="0" resultType="com.test.beans.Employee">
                <association property="dept"
                             select="com.test.dao.DepartMentMapper.getDeptById"
                             column="d_id">
                </association>
            </case>
            <!--男生;如果是男生,把last_name这一列的值赋值给email-->
            <case value="1" resultType="com.test.beans.Employee">
                <id column="id" property="id"/>
                <result column="last_name" property="lastName"/>
                <result column="last_name" property="email"/>
                <result column="gender" property="gender"/>
            </case>
        </discriminator>
    </resultMap>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值