栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis-plus

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis-plus

1.什么是mybatis-plus
MyBatis-Plus (opens new window)(简称 MP)是一个MyBatis (opens new window)的增强工具,在 MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。

 

2.mybatis的特性
  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
3.支持数据库
mysql 、 mariadb 、 oracle 、 db2 、 h2 、
hsql 、 sqlite 、 postgresql 、 sqlserver
4.快速入门 4.1创建springboot项目

4.1.1在项目中引入相关依赖

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.3.4
        

        
        
            com.alibaba
            druid
            1.1.19
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
注意:

       引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题。

4.1.2在入口类上添加注解

@SpringBootApplication
@MapperScan("com.briup.dao")
public class SpringbootMybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisplusApplication.class, args);
    }

}

4.1.3编写配置文件

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root

logging.level.root=info
logging.level.com.briup.dao=debug
4.2创建数据库表
DROP TABLE IF EXISTS user;

CREATE TABLE t_user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    username VARCHAr(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAr(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);
INSERT INTO t_user (id, username, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
 4.3编写实体类
package com.briup.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
@TableName("t_user")
public class User {
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    @TableField(value = "username")
    private String name;
    private Integer age;
    private String email;

}
4.4编写dao层接口
package com.briup.dao;

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.briup.bean.User;

public interface UserMapper extends baseMapper {
}
4.5测试
package com.briup.springbootmybatisplus;

import com.briup.bean.User;
import com.briup.dao.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringbootMybatisplusApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {

        List users = userMapper.selectList(null);
        users.forEach(System.out::println);

    }

}
5 常用注解说明

@TableName

  • 描述:表名注解,标识实体类对应的表
  • 使用位置:实体类
//lombok相关注解
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
//mybatis-plus注解
@TableName("t_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

}

@TableId

  • 描述:主键注解
  • 使用位置:实体类主键字段
  • 常用属性               
    •   value:String类型,指定实体类与表中对应的主键列名
    •   type:枚举类型,指定主键生成类型
package com.briup.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
@TableName("t_user")
public class User {
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;

}

@TableField

  • 描述:字段注解(非主键)
  • 使用位置:用在属性上
  • 常用属性               
    •   value:String类型,指定对应的数据库表中的字段名
    •   exist:boolean类型,表示是否为数据库中的列 true代表是数据库中的字段,false代表不是数据库中的字段
package com.briup.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
@TableName("t_user")
public class User {
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    @TableField(value = "username")
    private String name;
    private Integer age;
    private String email;
    //不映射数据库表中的任何字段
    @TableField(exist = false)
    private int aaa;

}
6.常用方法的使用 6.1查询方法
  • 查询所有
@Test
public void test(){  
    List users = userMapper.selectList(null);
    users.forEach(System.out::println);
}
  • 查询一个
@Test
public void test(){
    User user = userMapper.selectById(1);
    System.out.println("user = "+user);
}
  • 条件查询
@Test
public void test(){
     QueryWrapper wrapper = new QueryWrapper<>();
     //wrapper.eq("age",20);//设置等值查询
     //wrapper.lt("age",20);//设置小于查询
     wrapper.le("age",20);//设置小于等于查询
     List list = userMapper.selectList(wrapper);
     list.forEach(System.out::println);
}
  • 模糊查询
@Test
public void test(){ 
       QueryWrapper wrapper = new QueryWrapper<>();
        //中间包含
        //wrapper.like("username","t");
        //以t结尾
        //wrapper.likeLeft("username","t");
        //以t开头
        wrapper.likeRight("username","t");
        List list1 = userMapper.selectList(wrapper);
        list1.forEach(System.out::println);
}

like 相当于 %?%

likeLeft相当于 %?

likeRight相当于?%

6.2添加方法
  • 添加方法
@Test
public void test(){
  User entity = new User();
  entity.setName("tony").setAge(30).setEmail("tony@baomidu.com");
  userMapper.insert(entity);
}
6.2修改方法
  • 基于id修改
@Test
public void testUpdateById(){
    User user = userMapper.selectById("1");
    user.setAge(24);
    userMapper.updateById(user);
}
  • 基于条件修改
@Test
public void updatetest(){
  User u =n ew User();
  u.setName("jack");
  //将年龄是20岁的用户信息修改成名字叫jack
  QueryWrapper queryWrapper = new QueryWrapper();
  queryWrapper.eq("age",20);
  userMapper.update(user,queryWrapper);
}
6.2 删除方法
  • 基于id删除
@Test
 public void deleteTest(){
      userMapper.deleteById(1);
}
  • 基于条件批量删除
@Test
public void deleteTest(){
     //删除年龄大于等于20的用户
     QueryWrapper wrapper = new QueryWrapper<>();
     wrapper.ge("age",20);
     userMapper.delete(wrapper);
 }
7.mybatis-3.4.3.4分页查询 7.1预先配置

注意:使用分页查询必须设置mybatis-plus提供的分页插件,才能实现分页效果,且只限于单表查询,如果多表连接查询,分页插件无效。如果涉及到多表,可以采用子查询方式进行实现(即查一张表,再根据结果查询另一张表)。

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
 7.2分页查询
  • 非条件分页查询
 @Test
 public void findPageTest(){
       IPage page = new Page<>(1,2);
       page = userMapper.selectPage(page, null);
       List records = page.getRecords();
       records.forEach(System.out::println);
}
  • 条件分页查询
 @Test
 public void findPageWithConditionTest(){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.gt("age", 20);
        IPage page = new Page<>(2,2);
        page = userMapper.selectPage(page, wrapper);
        List records = page.getRecords();
        records.forEach(System.out::println);
 }
8.多数据源配置读写分离

为了确保数据库产品的稳定性,很多数据库拥有双机热备功能。也就是,第一台数据库服务器,是对外提供增删改业务的生产服务器;第二台数据库服务器,主要进行读的操作。

 

 8.1引入依赖
 

    com.baomidou
    dynamic-datasource-spring-boot-starter
    3.0.0
 8.2配置数据源
spring.datasource.primary=master  #指定默认数据源
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=UTF-8
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=root
spring.datasource.dynamic.datasource.slave1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.slave1.url=jdbc:mysql://localhost:3306/mybatisplus-1?characterEncoding=UTF-8
spring.datasource.dynamic.datasource.slave1.username=root
spring.datasource.dynamic.datasource.slave1.password=root
8.3构建多个数据库模拟多数据源 8.4@DS注解
  • 作用:用来切换数据源
  • 修饰范围:方法和类上、方法上注解优先级高于类上注解优先级
  • Values属性:切换数据库名称
8.5开发逻辑层
  • 业务接口
public interface UserService {

       List findAll();

       void save(User user);
}
  • 业务实现
@Service
@Transactional
public class UserServiceImpl  implements  UserService{
    @Autowired
    private UserMapper userMapper;


    @Override
    @DS("slave1")
    public List findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }
}
8.6测试
 @Test
 public void datasource_select_test(){
        List list = userService.findAll();
        list.forEach(System.out::println);
 }

 @Test
 public void datasource_save_test(){
        User user = new User();
        user.setAge(40).setName("save1").setEmail("save1@qq.com");
        userService.save(user);
 }
8.7测试结果

插入操作数据存入了master主库

检索操作数据是从slave1从库中检索出来的

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/680417.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号