• 12【MyBatis注解开发】


    三、Mybatis注解开发

    3.1 快速入门

    3.1.1 常用注解说明

    注解功能
    @Insert新增
    @Update更新
    @Delete删除
    @Select查询
    @Result结果集封装
    @Results与@Result 一起使用,封装多个结果集
    @One一对一结果集封装
    @Many一对多结果集封装

    3.1.2 注解实现开发

    • SQL语句:
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`  (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `birthday` date NULL DEFAULT NULL,
      `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    INSERT INTO `user` VALUES (1, '张三', '1999-02-04', '男', '佛山');
    INSERT INTO `user` VALUES (2, '李四', '1998-01-15', '女', '湛江');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 实体类:
    package com.dfbz.entity;
    
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    import java.util.List;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int  id;
        private String username;
        private Date birthday;
        private String sex;
        private String address;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • dao接口:
    package com.dfbz.dao;
    
    import com.dfbz.entity.User;
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    import java.util.List;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    public interface UserDao {
    
        @Select("select * from user where id=#{id}")
        User findById(int id);
    
        @Select("select * from user")
        List<User> findAll();
    
        @Insert("insert into user values(null,#{username},#{birthday},#{sex},#{address})")
        void save(User user);
    
        @Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
        void update(User user);
    
        @Delete("delete from user where id=#{id}")
        void delete(int id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 加载配置类:

    在这里插入图片描述

    • 测试类:
    package com.dfbz.test;
    
    import com.dfbz.dao.UserDao;
    import com.dfbz.entity.User;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.util.Date;
    import java.util.List;
    
    public class Demo01 {
    
        private SqlSessionFactoryBuilder builder;
    
        private SqlSessionFactory factory;
    
        private SqlSession session;
    
        private UserDao userDao;
    
        @Before
        public void before() throws IOException {
            builder=new SqlSessionFactoryBuilder();
            factory=builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
            session= factory.openSession();
            userDao=session.getMapper(UserDao.class);
        }
        @After
        public void after(){
            session.commit();
            session.close();
        }
    
        @Test
        public void save(){         //增加
            User user=new User();
            user.setUsername("小龙");
            user.setBirthday(new Date());
            user.setSex("男");
            user.setAddress("广州");
            userDao.save(user);
    
        }
        @Test
        public void delete(){
            userDao.delete(1);
        }
        @Test
        public void update(){
            User user=new User();
            user.setId(2);
            user.setUsername("张三");
            user.setBirthday(new Date());
            user.setSex("男");
            user.setAddress("广州");
            userDao.update(user);
    
        }
        @Test
        public void findById(){
            User user = userDao.findById(2);
            System.out.println(user);
        }
    
        @Test
        public void findAll(){
            List<User> userList = userDao.findAll();
            for (User user : userList) {
                System.out.println(user);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    3.2 注解实现一对一映射

    3.2.1 接口

    • Emp:
    package com.dfbz.entity;
    
    import lombok.Data;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    @Data
    public class Emp {
        private Integer id;
        private String name;
        private Integer age;
        private String addr;
        private Double salary;
    
        // 一个员工属于一个部门
        private Dept dept;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • Dept:
    package com.dfbz.entity;
    
    import lombok.Data;
    
    import java.util.List;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    @Data
    public class Dept {
        private Integer id;
        private String name;
        private String location;
    
        // 一个部门下有多个员工
        private List<Emp> empList;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • DeptDao:
    package com.dfbz.dao;
    
    
    import com.dfbz.entity.Dept;
    import org.apache.ibatis.annotations.Select;
    
    public interface DeptDao {
    
        @Select("select * from dept where id=#{id}")
        Dept findById(Integer id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • EmpDao:
    package com.dfbz.dao;
    
    
    import com.dfbz.entity.Dept;
    import com.dfbz.entity.Emp;
    import org.apache.ibatis.annotations.One;
    import org.apache.ibatis.annotations.Result;
    import org.apache.ibatis.annotations.Results;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.mapping.FetchType;
    
    public interface EmpDao {
    
    
        @Select("select * from emp where id=#{id}")
        @Results({
                @Result(id = true, property = "id", column = "id"),
                @Result(property = "name", column = "name"),
                @Result(property = "age", column = "age"),
                @Result(property = "addr", column = "addr"),
                @Result(property = "salary", column = "salary"),
                @Result(property = "dept", column = "dept_id", javaType = Dept.class,
                        one = @One(select = "com.dfbz.dao.DeptDao.findById",fetchType = FetchType.LAZY)
                ),
    
        })
        Emp findById(Integer id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    3.2.2 测试类

    @Test
    public void test1() {
        Emp emp = empDao.findById(1);
        System.out.println(emp);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.3 注解实现一对多映射

    3.2.1 接口

    • DeptDao:
    @Select("select * from dept where id=#{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "name",column = "name"),
            @Result(property = "location",column = "location"),
            @Result(property = "empList",column = "id",javaType = List.class,
                many = @Many(select = "com.dfbz.dao.EmpDao.findByDeptId",fetchType = FetchType.LAZY)
            )
    })
    Dept findDeptAllById(Integer id);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • EmpDao:
    @Select("select * from emp where dept_id=#{deptId}")
    List<Emp> findByDeptId(Integer deptId);
    
    • 1
    • 2

    3.2.2 测试类

    @Test
    public void test2() {
        Dept dept = deptDao.findDeptAllById(1);
        System.out.println(dept);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    ES6如何声明一个类?类如何继承?
    Postman启动问题:Could not open Postman
    字符函数和字符串函数(1)
    Jmeter书中不会教你的(99)——java request实例
    dubbo-admin 的安装
    论文投稿指南——收藏|SCI论文怎么投?
    python+appium自动化测试如何控制App的启动和退出
    1076 Forwards on Weibo
    【PAT甲级 - C++题解】1049 Counting Ones
    Java的String工具类源码
  • 原文地址:https://blog.csdn.net/Bb15070047748/article/details/128103156