• 使用discriminator实现鉴别器


    1在人员接口实现方法

    public Employee getEmpByIdStep(Integer id);

    2在映射文件进行配置

    <!-- public Employee getEmpByIdStep(Integer id);-->
    <select id="getEmpByIdStep" resultMap="MyEmpDis">
    select * from tbl_employee where id=#{id}
    </select>

    3写鉴别器

    <!-- <discriminator javaType=""></discriminator>
    鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
    封装Employee:
    如果查出的是女生:就把部门信息查询出来,否则不查询;
    如果是男生,把last_name这一列的值赋值给email;
    -->
    <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmpDis">
    <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.atguigu.mybatis.bean.Employee">
    <association property="dept"
    select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
    column="did">
    </association>
    </case>
    <!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
    <case value="1" resultType="com.atguigu.mybatis.bean.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>

    3在junit进行测试

    @Test
    public void test05() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
    EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
    Employee employee = mapper.getEmpByIdStep(4);
    System.out.println(employee);
    System.out.println(employee.getDept());
    }finally{
    openSession.close();
    }
    }

    结果如下:

    @Test
    public void test05() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();
    try{
    EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
    Employee employee = mapper.getEmpByIdStep(1);
    System.out.println(employee);
    System.out.println(employee.getDept());
    }finally{
    openSession.close();
    }
    }

    结果如下:

  • 相关阅读:
    Java [leetcode 33]Search in Rotated Sorted Array
    JAVA方法和本地方法(转载)
    Java集合框架
    常用排序算法
    Java [leetcode 32]Longest Valid Parentheses
    四大组件的生命周期
    Android Service即四大组件总结
    Java [leetcode 31]Next Permutation
    android 组件设置屏幕大小
    MenuInflater用法
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8549414.html
Copyright © 2020-2023  润新知