• MyBatis-Plus详解


    MyBatis-Plus

    MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

    官网 MyBatis-Plus

    连接池: 传统开发中,每一次请求都要建立一次数据库连接。每一次数据库连接,使用完后都得断开。频繁的数据库连接操作势必占用很多的系统资源,响应速度必定下降。另外,在高并发时,系统资源被毫无顾及的分配出去,如连接过多,也可能导致内存泄漏,服务器崩溃。

    解决方案: 为数据库连接建立一个“缓冲池”(连接池)。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕再放回去。通过设定连接池最大连接数来防止系统无休止的数据库连接。

    工作流程: 当客户端请求服务器,服务器需要使用连接对象操作数据库的数据。这时,需要从连接池中申请一个连接对象。连接池会分配一个空闲连接给该客户。如果连接池中没有空闲连接,就看有没有到达最大连接数。如果没有到达最大连接数,就创建新连接分配给客户。如果已经到达最大连接,那么,请求用户会等待一段时间,在等待时间内,有连接对象被释放,则分配给等待用户。等待时间结束后,还没有连接被释放,则返回null。


    Mybatis --- 环境搭建

    1、导入相关依赖

    1.    org.springframework.boot
    2.    spring-boot-starter-parent
    3.    2.4.2
    4.    
    5.    
    6.        mysql
    7.        mysql-connector-java
    8.        5.1.48
    9.    
    10.    
    11.        org.springframework.boot
    12.        spring-boot-starter
    13.    
    14.    
    15.        org.springframework.boot
    16.        spring-boot-starter-test
    17.        test
    18.    
    19.    
    20.        com.baomidou
    21.        mybatis-plus-boot-starter
    22.        3.4.3
    23.    
    24.    
    25.        junit
    26.        junit
    27.        4.12
    28.        test
    29.    
    30.    
    31.        com.alibaba
    32.        druid
    33.        1.2.9
    34.    

    2、创建实体类

    1. //声明该实体类映射的表名
    2. @TableName("t_product")
    3. public class ProductBean {
    4.    //表示该列为主键列,value表示该列映射的列名
    5.    //type = IdType.AUTO 表示该列的值使用自动增长列生成
    6.    @TableId(value = "pk_productId",type = IdType.AUTO)
    7.    private Integer id;
    8.    
    9.    //指定当前属性映射的列名
    10.    @TableField("p_name")
    11.    private String name;
    12.    @TableField("p_createDate")
    13.    private LocalDate createDate;
    14.    @TableField("p_price")
    15.    private Integer price;
    16. }

    3、在 resources 目录下,创建 application.yml 配置文件

    1. spring:
    2.  datasource:
    3.    driver-class-name: com.mysql.jdbc.Driver  #定义配置驱动类
    4.    username: root #mysql登录用户名
    5.    password: 123 #mysql登录密码
    6.    url: jdbc:mysql://localhost:12345/shopDB?characterEncoding=utf8&allowMultiQueries=true
    7.    type: com.alibaba.druid.pool.DruidDataSource #配置连接池
    8.    druid:
    9.      one:
    10.        max-active: 100 #最大连接数
    11.        min-idle: 20 #最小连接数
    12.        max-wait: 2000 #超时时间(ms)
    13. mybatis-plus:
    14.  configuration:
    15.    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置日志
    16.  type-aliases-package: com.project.bean #实体类所在包,允许用实体类类名作为别名
    17.  mapper-locations: classpath:*/*Mapper.xml #链接 mapper文件

    4、创建业务接口

    1. public interface IProductService {
    2.    public void add(ProductBean productBean);
    3.    public void del(Integer id);
    4.    public void update(Integer id,Integer price);
    5.    public List findAll();
    6.    public ProductBean findById(Integer id);
    7.    public List findByItem(String name,
    8. LocalDate startDate,LocalDate endDate);
    9. }

    5、创建 mapper 接口

    1. @Mapper
    2. public interface IProductMapper extends BaseMapper {
    3. }

    6、书写业务接口实现类

    1. @Service
    2. @Transactional//该类所有方法支持事务
    3. public class ProductServiceImpl implements IProductService {
    4.    @Autowired
    5.    private IProductMapper mapper;
    6.    @Override
    7.    public void add(ProductBean productBean) {
    8.        mapper.insert(productBean);//添加实体数据
    9.   }
    10.    @Override
    11.    public void del(Integer id) {
    12.        mapper.deleteById(id);//根据id删除实体数据
    13.   }
    14.    @Override
    15.    public void update(Integer id, Integer price) {
    16.        ProductBean productBean = new ProductBean();
    17.        productBean.setId(id);
    18.        productBean.setPrice(price);
    19.        mapper.updateById(productBean);//按id修改实体属性
    20.   }
    21.    @Override
    22.    public List findAll() {
    23.        return mapper.selectList(null);//查询所有
    24.   }
    25.    @Override
    26.    public ProductBean findById(Integer id) {
    27.        return mapper.selectById(id);//按id查询实体对象
    28.   }
    29.    @Override
    30.    public List findByItem(String name,
    31. LocalDate startDate, LocalDate endDate) {
    32.        QueryWrapper qw = new QueryWrapper<>();//条件集合
    33.        if (name != null && name.length() != 0){
    34.            qw.like("p_name",name);//like 模糊查询
    35.       }
    36.        if (startDate != null){
    37.            qw.ge("p_creatDate",startDate);//ge 大于等于
    38.       }
    39.        if (endDate != null){
    40.            qw.le("p_createDate",endDate);//le 小于等于
    41.       }
    42.        return mapper.selectList(qw);//按条件查询
    43.   }
    44. }

    7、测试类

    1. @RunWith(SpringRunner.class)
    2. @SpringBootTest(classes = Main.class)//启动类类模板
    3. public class ProductTest {
    4.    @Autowired
    5.    private IProductService service;
    6.    @Test
    7.    public void test(){
    8. //       service.add(new ProductBean("999感冒灵",
    9. LocalDate.parse("2022-06-06"),18));
    10.        System.out.println(service.findAll());
    11.   }
    12. }

    分页查询

    1、创建配置类,定义数据库 SQL 语句的方言。Mybatis-plus会根据配置的方言,产生分页的 SQL 语句

    1. @Configuration
    2. public class MyBatisPlusConfig {
    3.    @Bean
    4.    public MybatisPlusInterceptor mybatisPlusInterceptor() {
    5.        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    6.        interceptor.addInnerInterceptor(
    7.                new PaginationInnerInterceptor(DbType.MYSQL));
    8.        return interceptor;
    9.    }
    10. ​}

    2、定义业务接口方法

    1. /**
    2. * 动态条件分页查询
    3. * @param pageNO 页码
    4. * @param name 姓名
    5. * @param startDate 生产起始日期
    6. * @param endDate 生成结束日期
    7. * @return 分页对象
    8. */
    9. public IPage findByItem(Integer pageNO,
    10. String name, LocalDate startDate,LocalDate endDate);

    3、定义 mapper 接口

    1. @Mapper
    2. public interface IProductMapper extends BaseMapper {
    3. }

    4、书写业务方法

    1. @Override
    2. public IPage findByItem(Integer pageNO,
    3. String name, LocalDate startDate, LocalDate endDate) {
    4.    QueryWrapper qw = new QueryWrapper<>();
    5.    if (name != null && name.length() != 0){
    6.        qw.like("p_name",name);
    7.   }
    8.    if (startDate != null){
    9.        qw.ge("p_createDate",startDate);
    10.   }
    11.    if (endDate != null){
    12.        qw.le("p_createDate",endDate);
    13.   }
    14.    return mapper.selectPage(new Page(pageNO,3),qw);
    15. }

    5、测试类

    1. @RunWith(SpringRunner.class)
    2. @SpringBootTest(classes = PlusMain.class)
    3. public class Test {
    4.    @Autowired
    5.    private IProductService service;
    6.    @org.junit.Test
    7.    public void test(){
    8. //       System.out.println(service.findAll());
    9.        IPage ip = service.findByItem(1,"",null,null);
    10.        System.out.println(ip.getRecords()//得到当前数据
    11.                +" "+ip.getTotal()//得到总记录数
    12.                +" "+ip.getPages()//总页数
    13.                +" "+ip.getCurrent()//得到页码
    14.                +" "+ip.getSize()//得到每页记录数
    15.                 );
    16.   }
    17. }

    Mybatis-plus 关联操作

    一对多:

    1、创建实体类

    1. /**
    2. * 部门实体类
    3. */
    4. @TableName("t_dept")
    5. public class DeptBean {
    6.    @TableId(value = "pk_deptId",type = IdType.AUTO)
    7.    private Integer id;
    8.    @TableField("d_name")
    9.    private String name;
    10.    @TableField(exist = false)//标识该属性没有对应的列
    11.    private Integer emNum;
    12.    @TableField(exist = false)//标识该属性没有对应的列
    13.    private List emList;
    14. }
    15. /**
    16. * 员工实体类
    17. */
    18. @TableName("t_employee")
    19. public class EmployeeBean {
    20.    @TableId(value = "pk_emId",type = IdType.AUTO)
    21.    private Integer id;
    22.    @TableField("e_name")
    23.    private String name;
    24.    @TableField("e_job")
    25.    private String job;
    26.    @TableField("e_birthday")
    27.    private LocalDate birthday;
    28.    @TableField("fk_deptId")
    29.    private Integer deptId;
    30.    @TableField(exist = false)
    31.    private DeptBean dept;
    32. }

    注意:如果一个属性没有对应的列,必须加上@TableField(exist = false)。否则,maybatis-plus会认为数据库表中有一个和该属性同名列。

    2、建立业务接口

    1. /**
    2. *部门业务接口
    3. */
    4. public interface IDeptService {
    5.    /**
    6.     * 查询所有部门,同时统计每个部门的人数
    7.     * @return 部门集合
    8.     */
    9.    public List findAll();
    10.    /**
    11.     * 级联添加,添加部门,同时添加该部门的员工集合
    12.     * @param dept 部门对象
    13.     * @param emList 新员工集合
    14.     */
    15.    public void add(DeptBean dept, List emList);
    16.    /**
    17.     * 删除部门,同时级联删除部门的员工
    18.     * @param id 部门ID
    19.     */
    20.    public void delCasede(Integer id);
    21.    /**
    22.     * 删除部门,同时将该部门员工外键设置为null
    23.     * @param id 部门ID
    24.     */
    25.    public void delSerNull(Integer id);
    26.    /**
    27.     * 按id查询部门,同时查询该部门中所有的员工
    28.     * @param id 部门id
    29.     * @return 部门对象
    30.     */
    31.    public DeptBean findById(Integer id);
    32. }
    33. /**
    34. * 员工业务接口
    35. */
    36. public interface IEmployeeService {
    37.    /**
    38.     * 添加员工
    39.     * @param employee 员工对象
    40.     */
    41.    public void add(EmployeeBean employee);
    42.    /**
    43.     * 动态条件分页查询,同时查询每个员工所在部门的名称
    44.     * @param pageNO 页码
    45.     * @param deptName 部门名称
    46.     * @param name 员工姓名
    47.     * @return 分页对象
    48.     */
    49.    public IPage findByItem(Integer pageNO,
    50. String deptName,String name);
    51.    /**
    52.     * 按id查询员工,同时查询员工的部门信息
    53.     * @param id 员工编号
    54.     * @return 员工对象33
    55.     */
    56.    public EmployeeBean findById(Integer id);
    57. }

    3、建立 Mapper 接口

    1. /**
    2. *部门 mapper 接口
    3. */
    4. @Mapper
    5. public interface IDeptMapper extends BaseMapper {
    6.    @Select("SELECT d.*,COUNT(e.`pk_emId`) emNum FROM t_dept d LEFT JOIN
    7. t_employee e ON d.`pk_deptId`=e.`fk_deptId`\n" +
    8.            "GROUP BY d.`pk_deptId`")
    9.    @ResultMap("deptMap")
    10.    public List findAll();
    11.    @Delete("delete from t_employee where fk_deptId=#{id};" +
    12.            "delete from t_dept where pk_deptId=#{id};")
    13.    public void delCasede(Integer id);
    14.    @Delete("update t_employee set fk_deptId=null where fk_deptId=#{id};" +
    15.            "delete from t_dept where pk_deptId=#{id};")
    16.    public void delSetNull(Integer id);
    17. }
    18. /**
    19. *员工 mapper 接口
    20. */
    21. @Mapper
    22. public interface IEmployeeMapper extends BaseMapper {
    23.    public void addMore(@Param("deptId") Integer deptId,
    24. @Param("emList") List emList);
    25.    public IPage findByItem(Page pageNO,
    26. @Param("deptName") String deptName,@Param("name") String name);
    27. }

    对于联表查询的结果集,动态条件查询、循环,都需要在 mapper 文件中完成。

    4、书写 mapper 文件

    IDeptMapper:

    1. "com.project.mapper.IDeptMapper">
    2.    "deptMap" type="DeptBean">
    3.        "id" column="pk_deptId">
    4.        "name" column="d_name">
    5.        "emNum" column="emNum">
    6.    

    IEmployeeMapper:

    1. "com.project.mapper.IEmployeeMapper">
    2.    "addMore">
    3.        insert into t_employee (e_name,e_job,e_birthday,fk_deptId)
    4. values
    5.        "emList" item="em" separator=",">
    6.           (#{em.name},#{em.job},#{em.birthday},#{deptId})
    7.        
    8.    
    9.    "emMap" type="EmployeeBean">
    10.        "pk_emId" property="id">
    11.        "e_name" property="name">
    12.        "e_job" property="job">
    13.        "e_birthday" property="birthday">
    14.        "d_name" property="dept.name">
    15.    
    16.    

    5、书写业务方法

    1. /**
    2. * 部门业务方法
    3. */
    4. @Service
    5. @Transactional
    6. public class DeptServiceImpl implements IDeptService {
    7.    @Autowired
    8.    private IDeptMapper deptMapper;
    9.    @Autowired
    10.    private IEmployeeMapper employeeMapper;
    11.    @Override
    12.    public List findAll() {
    13.        return deptMapper.findAll();
    14.   }
    15.    @Override
    16.    public void add(DeptBean dept, List emList) {
    17.        deptMapper.insert(dept);
    18.        employeeMapper.addMore(dept.getId(),emList);
    19.   }
    20.    @Override
    21.    public void delCasede(Integer id) {
    22.        deptMapper.delCasede(id);
    23.   }
    24.    @Override
    25.    public void delSerNull(Integer id) {
    26.        deptMapper.delSetNull(id);
    27.   }
    28.    @Override
    29.    public DeptBean findById(Integer id) {
    30.        DeptBean dept = deptMapper.selectById(id);
    31.        QueryWrapper qw = new QueryWrapper<>();
    32.        qw.eq("fk_deptId",id);
    33.        dept.setEmList(employeeMapper.selectList(qw));
    34.        return dept;
    35.   }
    36. }
    37. /**
    38. * 员工业务方法
    39. */
    40. @Service
    41. @Transactional
    42. public class EmployeeServiceImpl implements IEmployeeService {
    43.    @Autowired
    44.    IEmployeeMapper employeeMapper;
    45.    @Autowired
    46.    IDeptMapper deptMapper;
    47.    @Override
    48.    public void add(EmployeeBean employee) {
    49.        employeeMapper.insert(employee);
    50.   }
    51.    @Override
    52.    public IPage findByItem(Integer pageNO,
    53. String deptName, String name) {
    54.        return employeeMapper.findByItem(new Page(pageNO,3),deptName,name);
    55.   }
    56.    @Override
    57.    public EmployeeBean findById(Integer id) {
    58.        EmployeeBean em = employeeMapper.selectById(id);
    59.        em.setDept(deptMapper.selectById(em.getDeptId()));
    60.  ··      return em;
    61.   }
    62. }

    统计查询记录数

    1. QueryWrapper qw = new QueryWrapper<>();
    2. qw.eq("fk.classId",classId);
    3. Integer num = studentMapper.selectCount(qw);
  • 相关阅读:
    IDEA创建SparkSQL程序_大数据培训
    博途PLC S7-1200/1500 ModbusTcp通信SCL代码篇(轮询)
    Sentinel 分布式系统
    复合函数的结合律证明
    git常用的命令
    JUC并发编程:第二季
    vue源码分析-响应式系统(二)
    OceanBase 系统架构初探
    如何用idm下载迅雷文件 idm怎么安装到浏览器 idm怎么设置中文
    使用HTML制作静态网站作业——我的校园运动会(HTML+CSS)
  • 原文地址:https://blog.csdn.net/weixin_66564094/article/details/126696648