美文网首页
MyBatis 加强 ("多对一")

MyBatis 加强 ("多对一")

作者: superNeil | 来源:发表于2020-05-30 00:44 被阅读0次

    不破楼兰终不还 !
    不愿做咸鱼!

    记住步骤(套路) :

    1. 明需求 -->2.表设计-->3.类设计-->4.Mapper接口和Mapper.xml文件-->5.编写单元测试 类

    下面给大家演示一个例子 :

    我们按上面地的步骤一步一步来 , 丝毫不慌 ! 十分简单 !

    1. 明需求

    1.保存一个部门和两个员工,且这两个员工都是这个部门的。

    2.根据员工 id 查询员工,并知道该员工的所在的部门。

    1. 表设计


      image-20200530002519340.png

      3.类设计( 根据需求和表设计 可以确定类应该如何设计 ! )

    package cn.wolfcode.domain;
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    @Setter
    @Getter
    @ToString
    public class Department {
        private Long id;
        private String name;
        //部门表
    }
    
    package cn.wolfcode.domain;
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    @Setter
    @Getter
    @ToString
    public class Employee {
        private Long id;
        private String name;
        // 关联属性
        private Department dept;
    }
    

    4.Mapper接口和Mapper.xml文件

    package cn.wolfcode.mapper;
    import cn.wolfcode.domain.Department;
    public interface DepartmentMapper {
        /**
         * 保存操作
         * @param dept
         */
        void save(Department dept);
        /**
         * 查询 部门表
         * @param id
         * @return
         */
        Department get(Long id);
    }
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.wolfcode.mapper.DepartmentMapper">
        <!--
        useGeneratedKeys=true 获取数据库保存数据的的主键值
        keyProperty="id" 主键设置对象的 id 属性
        -->
        
        <!--保存的sql语句-->
        <insert id="save" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO department(name) VALUES(#{name})
        </insert>
        
        <!--***************隔开看,一步步理解*********************-->
        
        <!--查询操作 通过id 获取 id , name-->
        <select id="get" resultType="Department">
        SELECT id, name FROM department WHERE id = #{id}
        </select>
    </mapper>
    
    package cn.wolfcode.mapper;
    
    import cn.wolfcode.domain.Department;
    import cn.wolfcode.domain.Employee;
    
    import java.util.List;
    
    public interface EmployeeMapper {
        void save(Employee employee);
    
        //查询单条数据  错误示范
        Employee get(Long id);
    
        //查询单条数据  正确示范
        Employee get1(Long id);//使用方法 1 
        Employee get2(Long id);//使用方法 2 推荐 , 往下看
    
    
        List<Employee> listAll();
    }
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.wolfcode.mapper.EmployeeMapper">
        <!--
         useGeneratedKeys=true 获取数据库保存数据的的主键值
         keyProperty="id" 主键设置对象的 id 属性
         -->
        <!--保存的sql语句-->
        <insert id="save" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO employee(name, deptId) VALUES(#{name}, #{dept.id})
        </insert>
    
    
        <!--查询的sql语句-->
        <!--错误示范的 对应sql  这条查不出来的数据 deptId  : null -->
        <!--原因 : 数据对应不上 可以看看 Employee实体类的设计 一目了然-->
        <select id="get" resultType="Employee">
            SELECT id,name,deptId FROM employee WHERE id=#{id}
        </select>
        <!--所以上面这条查询的sql语句,不成立!-->
    
        <!--方法1-->
        <!--正确的查询语句-->
        <resultMap id="baseResultMap1" type="Employee">
            <!-- 什么列名对应值封装到对象的什么属性上 -->
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <result column="deptId" property="dept.id"/>
        </resultMap>
    
        <!--正确示范的 对应sql-->
        <select id="get1" resultMap="baseResultMap1">
         SELECT id,name,deptId FROM employee WHERE id=#{id}
        </select>
    
    
        <!--方法2 推荐-->
        <resultMap type="Employee" id="baseResultMap2">
            <!-- 什么列名对应值封装到对象的什么属性上 -->
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <!-- 使用额外 SQL
             association 针对的关联属性配置,非集合类型
             select 发送什么额外 SQL
              column 发送额外 SQL 参数取上一条 SQL 哪个列的值
                property 封装员工对象的什么属性 -->
            <association select="cn.wolfcode.mapper.DepartmentMapper.get" column="deptId" property="dept"
                         javaType="Department"/>
        </resultMap>
        <select id="get2" resultMap="baseResultMap2">
            SELECT id,name,deptId FROM employee WHERE id=#{id}
        </select>
    
    
        <select id="listAll" resultMap="baseResultMap2">
          SELECT id, name, deptId FROM employee
        </select>
    
    
    </mapper>
    

    5.编写单元测试

    保存操作的测试 :
    public class EmployeeMapperTest {
        /**
         * 保存操作
         *
         * @throws Exception
         */
        @Test
        public void testSave() throws Exception {
            //创建部门类 对象  并设置值
            Department department = new Department();
            department.setName("财务部");
    
            //创建员工类 对象  并设置值
            Employee employee1 = new Employee();
            Employee employee2 = new Employee();
    
            employee1.setName("张无忌");
            employee1.setDept(department);
    
            employee2.setName("周芷诺");
            employee2.setDept(department);
    
            SqlSession session = MyBatisUtil.getSession();
            //获取接口
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            //获取接口
            DepartmentMapper departmentMapper = session.getMapper(DepartmentMapper.class);
            //注意  先保存 部门表
            //调用 departmentMapper 方法
            departmentMapper.save(department);
    
            //调用 employeeMapper 方法
            employeeMapper.save(employee1);
            employeeMapper.save(employee2);
            //开启事务
            session.commit();
            //关闭资源
            session.close();
        }
    }
    

    查询操作的测试 :

    public class Many2OneTest {
    
        /**
         * 错误  查询sql 的测试
         * 结果 : DEBUG [main] - ==>  Preparing: SELECT id,name,deptId FROM employee WHERE id=?
         *        Employee(id=1, name=张无忌, dept=null)
         * @throws Exception
         */
        @Test
        public void testGet() throws Exception {
            SqlSession session = MyBatisUtil.getSession();
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.get(1L);
            System.out.println(employee);
            session.commit();
            session.close();
        }
    
        /**
         * 正确  查询sql 的测试
         * 结果 :DEBUG [main] - ==>  Preparing: SELECT id, name FROM department WHERE id = ?
         *        Employee(id=1, name=张无忌, dept=Department(id=1, name=财务部))
         * @throws Exception
         */
        @Test
        public void testGet1() throws Exception {
            SqlSession session = MyBatisUtil.getSession();
            // 获取员工接口
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            //通过接口执行方法 获取 员工类对象
            Employee employee = employeeMapper.get1(1L);
            //因为 员工对象获取到了 并且得到 dept.id , 所以 通过
            Long id = employee.getDept().getId();
    
            DepartmentMapper departmentMapper = session.getMapper(DepartmentMapper.class);
            Department department = departmentMapper.get(id);
            employee.setDept(department);
            //打印 员工对象
            System.out.println(employee);
    
            //执行事务
            //关闭资源
            session.commit();
            session.close();
        }
    
        @Test
        public void testGet2() throws Exception {
            SqlSession session = MyBatisUtil.getSession();
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.get2(1L);
            System.out.println(employee);
            session.commit();
            session.close();
        }
    
        @Test
        public void testListAll(){
            SqlSession session = MyBatisUtil.getSession();
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            List<Employee> employees = employeeMapper.listAll();
            System.out.println(employees);
            session.close();
        }
    
    
    }
    

    相关文章

      网友评论

          本文标题:MyBatis 加强 ("多对一")

          本文链接:https://www.haomeiwen.com/subject/gqwqzhtx.html