zoukankan      html  css  js  c++  java
  • 使用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();
    }
    }

    结果如下:

  • 相关阅读:
    hdu 5723 Abandoned country 最小生成树 期望
    OpenJ_POJ C16G Challenge Your Template 迪杰斯特拉
    OpenJ_POJ C16D Extracurricular Sports 打表找规律
    OpenJ_POJ C16B Robot Game 打表找规律
    CCCC 成都信息工程大学游记
    UVALive 6893 The Big Painting hash
    UVALive 6889 City Park 并查集
    UVALive 6888 Ricochet Robots bfs
    UVALive 6886 Golf Bot FFT
    UVALive 6885 Flowery Trails 最短路
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8549414.html
Copyright © 2011-2022 走看看