zoukankan      html  css  js  c++  java
  • 使用collection查询集合属性

    介绍resultMap中使用collection查询集合属性

    业务需求,查询部门中的多个人员

    public class Department {

    private Integer id;
    private String departmentName;
    private List<Employee> emps;

    setter和getter省略

    }

    public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    private String gender;
    private Department dept;

    setter和getter省略

    }

    1。在department接口写方法

    public Department getDeptByIdPlus(Integer id);

    2.找到映射文件写

    <!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则 -->
    <resultMap type="com.atguigu.mybatis.bean.Department" id="MyDept">
    <id column="did" property="id"/>
    <result column="dname" property="departmentName"/>
    <!--
    collection定义关联集合类型的属性的封装规则
    ofType:指定集合里面元素的类型
    -->

    <collection property="emps" ofType="com.atguigu.mybatis.bean.Employee">
    <!-- 定义这个集合中元素的封装规则 -->
    <id column="eid" property="id"/>
    <result column="last_name" property="lastName"/>
    <result column="email" property="email"/>
    <result column="gender" property="gender"/>
    </collection>
    </resultMap>
    <!-- public Department getDeptByIdPlus(Integer id); -->
    <select id="getDeptByIdPlus" resultMap="MyDept">
    SELECT d.id did,d.dname dname,
    e.id eid,e.last_name last_name,e.email email,e.gender gender
    FROM department d
    LEFT JOIN tbl_employee e
    ON d.id=e.did
    WHERE d.id=#{id}
    </select>

    3进行测试

    @Test
    public void test06() throws IOException{
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession openSession = sqlSessionFactory.openSession();

    try{
    DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
    Department department = mapper.getDeptByIdPlus(1);
    System.out.println(department);
    System.out.println(department.getEmps());

    }finally{
    openSession.close();
    }
    }

    }

    运行结果如下:

  • 相关阅读:
    mysql查询字段取前3位,后3位,中间3位,去除前3位,去除后3位
    10月份四季度
    JavaScript箭头函数的立即执行函数实现三元表达式执行多条语句
    JavaScript判断是否是同一天
    项目经理:是兄弟就一起加班吧
    技术人员转型项目经理的角色转换
    项目经理入职后,如何快速管理项目
    如何解决项目成员之间的冲突?
    提高各方面沟通效率,是项目经理该去做的事
    项目计划太复杂?试试思维导图
  • 原文地址:https://www.cnblogs.com/zhangzhiqin/p/8549031.html
Copyright © 2011-2022 走看看