[mybatis]映射文件_select_resultMap_discriminator鉴别器

discriminator

    鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为 封装Employee: 如果查出的是女生;就把部门信息查询出来,否则不查询 如果查出的是男生;把last_name这一列的值赋给email
<resultMap id="MyEmpDis" type="com.atguigu.mybatis.bean.Employee">

        <id column="id" property="id"></id>
        <result column="last_name" property="lastName"></result>
        <result column="email" property="email"></result>

        <result column="gender" property="gender"></result>

        <!--
        column:指定判定的列名
        javaType:列值对应的java类型
        -->

        <discriminator javaType="string" column="gender">
            <!--            女生
            resultType:指定封装的结果类型,不能缺少
            -->
            <case value="0" resultType="com.atguigu.mybatis.bean.Employee">


                <association property="dept" select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
                             column="d_id"></association>

            </case>
            <!--            男生-->
            <case value="1" resultType="com.atguigu.mybatis.bean.Employee">

                <id column="id" property="id"></id>
                <result column="last_name" property="lastName"></result>
                <result column="last_name" property="email"></result>

                <result column="gender" property="gender"></result>

            </case>
        </discriminator>

    </resultMap>
    <!--    public Employee getEmpByIdStep(Integer id);-->
    <select id = "getEmpByIdStep" resultMap="MyEmpDis">
        select * from tb1_employee where id = #{id}
    </select>
@Test
    public void test04() throws IOException {
          
   
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try
        {
          
   
            EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);


            Employee employee = mapper.getEmpByIdStep(3);

            System.out.println(employee);

            System.out.println(employee.getDept());

        }finally {
          
   

            sqlSession.close();

        }
    }
经验分享 程序员 微信小程序 职场和发展