【MyBatis-Plus】从基础入门到代码生成器

一、基础入门

1.导入依赖包

1.1 mybatis-plus连接依赖

<dependency>  
    <groupId>com.baomidou</groupId>  
    <artifactId>mybatis-plus-boot-starter</artifactId>  
    <version>3.5.2</version>  
</dependency>  
<dependency>  
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
    <scope>runtime</scope>  
</dependency>

1.2 Druid连接依赖(Alibaba连接池)

<dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>druid</artifactId>  
    <version>1.2.12</version>  
</dependency>

2.properties文件配置

2.1 连接配置

# 连接类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 连接驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

2.2 日志输出配置

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3.创建实体类User

@Data
public class User {
    private Long id;
    private String name;
    private String password;
    private Integer age;
    private String tel;
}

4.创建接口类Mapper

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

5.创建测试类进行测试

@SpringBootTest
class BaseTest {
    
    @Autowired
    private UserMapper userMapper;

    @Test
    void testSave(){
        User user = new User();
        user.setName("Jack");
        user.setAge(24);
        user.setPassword("123");
        user.setTel("123");
        userMapper.insert(user);
    }

    @Test
    void testDelete(){
        userMapper.deleteById(1581180294937874433L);
    }

    @Test
    void testUpdate(){
        User user = new User();
        user.setId(1L);
        user.setTel("12356");
        userMapper.updateById(user);
    }

    @Test
    void testGetAll() {
        System.out.println(userMapper.selectList(null));
    }

    @Test
    void testGetById(){
        System.out.println(userMapper.selectById(1L));
    }
}

二、MP分页

1.添加分页拦截器

@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mpInterceptor(){
        // 1.定义MP拦截器
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
        // 2.添加具体的拦截器
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mpInterceptor;
    }
}

2.分页测试

@SpringBootTest
public class MPTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void testGetByPage() {
        IPage page = new Page(1, 2);
        System.out.println(userMapper.selectPage(page, null));
        System.out.println("当前页码值:" + page.getCurrent());
        System.out.println("每页显示数:" + page.getSize());
        System.out.println("总页数:" + page.getPages());
        System.out.println("数据总数:" + page.getTotal());
        System.out.println("分页后数据:" + page.getRecords());
    }
}

三、DQL编程控制

1.按条件查询

@SpringBootTest
public class DQLTest01 {

    @Autowired
    private UserMapper userMapper;

    /**
     * 方式一:按条件查询
     */
    @Test
    void testGetAll01(){
        QueryWrapper qw = new QueryWrapper();
        qw.lt("age", 18);
        System.out.println(userMapper.selectList(qw));
    }

    /**
     * 方式二:lambda格式按条件查询
     */
    @Test
    void testGetAll02(){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().lt(User::getAge, 10);
        System.out.println(userMapper.selectList(qw));
    }

    /**
     * 方式三:推荐 lambda格式按条件查询
     */
    @Test
    void testGetAll03(){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.lt(User::getAge, 10);
        System.out.println(userMapper.selectList(lqw));
    }

    /**
     * lambda格式多条件 and 查询
     */
    @Test
    void testGetAll04(){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.lt(User::getAge, 30).gt(User::getAge,10);
        System.out.println(userMapper.selectList(lqw));
    }

    /**
     * lambda格式多条件 or 查询
     */
    @Test
    void testGetAll05(){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.lt(User::getAge, 10).or().gt(User::getAge,30);
        System.out.println(userMapper.selectList(lqw));
    }
}

2.条件查询-null值处理

2.1 封装entity类查询条件UserQuery

@Data
public class UserQuery extends User {
    private Integer age2;
}

2.2 进行测试

@Test
void testGetAll06() {
    // 模拟页面传递过来的查询数据
    UserQuery uq = new UserQuery();
    // uq.setAge(10);
    uq.setAge2(30);

    // null判定
    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
    // 先判断第一个参数是否为true,如果为true连接当前条件
    lqw.lt(null != uq.getAge2(), User::getAge, uq.getAge2())
        .gt(null != uq.getAge(), User::getAge, uq.getAge());
    System.out.println(userMapper.selectList(lqw));
}

3.查询投影

/**
 * 方式一:推荐 lambda格式
 */
@Test
void testGetAll07() {
    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
    lqw.select(User::getId, User::getName, User::getAge);
    System.out.println(userMapper.selectList(lqw));
}

/**
 * 方式二:推荐 QueryWrapper格式
 */
@Test
void testGetAll08() {
    QueryWrapper<User> qw = new QueryWrapper<>();
    qw.select("id", "name", "age");
    System.out.println(userMapper.selectList(qw));
}

/**
 * 查询数据总数
 */
@Test
void testGetAll09() {
    QueryWrapper<User> qw = new QueryWrapper<>();
    qw.select("count(*) as count");
    System.out.println(userMapper.selectMaps(qw));
}

/**
 * 分组查询
 */
@Test
void testGetAll10() {
    QueryWrapper<User> qw = new QueryWrapper<>();
    qw.select("count(*) as count, tel");
    qw.groupBy("tel");
    System.out.println(userMapper.selectMaps(qw));
}

4.条件匹配

/**
 * =匹配
 */
@Test
void testGetAll11() {
    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
    lqw.eq(User::getName, "Jerry").eq(User::getPassword, "jerry");
    System.out.println(userMapper.selectOne(lqw));
}

/**
 * 范围匹配
 */
@Test
void testGetAll12() {
    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
    // 范围查询 lt le gt ge eq between
    lqw.between(User::getAge, 10, 30);
    System.out.println(userMapper.selectList(lqw));
}

/**
 * 模糊匹配
 */
@Test
void testGetAll13() {
    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
    // like likeRight likeLeft
    lqw.like(User::getName, "J");
    System.out.println(userMapper.selectList(lqw));
}

四、字段映射

1.SQL

CREATE TABLE `mybatis_plus`.`Untitled`  (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `pwd` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `age` int NOT NULL,
  `tel` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1581180294937874434 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

2.实体类User

@TableField

  • value:对应table里的字段名
  • select:是否参与查询
  • exist:是否是table里字段,默认为true
@Data
@TableName("tbl_user")
public class User {
    
    private Long id;
    
    private String name;
    
    @TableField(value = "pwd", select = false)
    private String password;
    private Integer age;
    
    private String tel;
    
    @TableField(exist = false)
    private Integer online;
}

五、CRUD

1. ID生成策略

1.1 实体类User

@TableId

  • type:ID自增策略
    • IdType.AUTO:使用数据库id自增策略控制id生产
    • IdType.NONE:不设置id生成策略
    • IdType.INPUT:用户手动输入id
    • IdType.ASSIGN_ID:雪花算法生成id
    • IdType.ASSIGN_UUID:以UUID生成算法作为id生成策略

@TableField

  • value:对应table里的字段名
  • select:是否参与查询
  • exist:是否是table里字段,默认为true
@Data
@TableName("tbl_user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    @TableField(value = "pwd", select = false)
    private String password;
    private Integer age;
    private String tel;
    @TableField(exist = false)
    private Integer online;
}

1.2 也可以在properties文件中设置

# 设置id生成策略
mybatis-plus.global-config.db-config.id-type=assign_id
# 设置table名前缀
mybatis-plus.global-config.db-config.table-prefix=tbl_

2.多数据操作

@SpringBootTest
public class CRUDTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void testDelete(){
        List<Long> list = new ArrayList<>();
        list.add(5L);
        list.add(6L);
        list.add(7L);
        userMapper.deleteBatchIds(list);
    }

    @Test
    void testSelect(){
        List<Long> list = new ArrayList<>();
        list.add(1L);
        list.add(2L);
        list.add(3L);
        userMapper.selectBatchIds(list);
    }
}

3.逻辑删除

3.1 SQL

添加deleted字段

CREATE TABLE `mybatis_plus`.`Untitled`  (
  `id` bigint NOT NULL DEFAULT 0,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `pwd` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `age` int NOT NULL,
  `tel` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `deleted` int NULL DEFAULT 0,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1581180294937874434 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

3.2 实体类User

@TableLogic

  • value:未删
  • delval:已删
@Data
@TableName("tbl_user")
public class User {
    
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    
    private String name;
    
    @TableField(value = "pwd", select = false)
    private String password;
    
    private Integer age;
    
    private String tel;
    
    @TableField(exist = false)
    private Integer online;
    
    // 逻辑删除字段,标记当前记录是否被删除
    @TableLogic(value = "0", delval = "1")
    private Integer deleted;
}

3.3 也可以在properties文件中配置

# 逻辑删除策略
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

3.4 测试

@Test
void testLogicTest() {
    userMapper.deleteById(4L);
}

六、乐观锁

1.SQL

添加version字段

CREATE TABLE `mybatis_plus`.`Untitled`  (
  `id` bigint NOT NULL DEFAULT 0,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `pwd` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `age` int NOT NULL,
  `tel` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `deleted` int NULL DEFAULT 0,
  `version` int NULL DEFAULT 1,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1581180294937874434 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

2.实体类User

@Data
@TableName("tbl_user")
public class User {
    
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    
    private String name;
    
    @TableField(value = "pwd", select = false)
    private String password;
    
    private Integer age;
    
    private String tel;
    
    @TableField(exist = false)
    private Integer online;
    
    // 逻辑删除字段,标记当前记录是否被删除
    @TableLogic(value = "0", delval = "1")
    private Integer deleted;
    
    @Version
    private Integer version;
}

3.添加拦截器

@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mpInterceptor(){
        // 1.定义MP拦截器
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
        // 2.添加具体的拦截器
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        // 3.添加乐观锁的拦截器
        mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mpInterceptor;
    }
}

4.测试

@Test
void testLock(){
    // 1.先通过要修改的数据id将当前数据查询出来
    User user = userMapper.selectById(3L);
    // 2.将要修改的属性逐一设置进去
    user.setName("Jock");
    userMapper.updateById(user);
}

七、代码生成器

1.导入依赖包

<!--代码生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.1.1</version>
</dependency>
<!--velocity模板引擎-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

2.SQL

CREATE TABLE `mybatis_plus`.`Untitled`  (
  `id` int NOT NULL,
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `price` double NULL DEFAULT NULL,
  `deleted` int NULL DEFAULT 0,
  `version` int NULL DEFAULT 1,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

3.创建代码生成器

public class Generator {
    public static void main(String[] args) {
        AutoGenerator autoGenerator = new AutoGenerator();
        // 代码生成
        DataSourceConfig dataSource = new DataSourceConfig();
        dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        autoGenerator.setDataSource(dataSource);

        // 设置全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        // 设置代码生成路径
        globalConfig.setOutputDir(System.getProperty("user.dir") + "\\src\\main\\java");
        // 生成完毕后是否打开
        globalConfig.setOpen(false);
        // 设置作者
        globalConfig.setAuthor("Jack");
        // 设置是否覆盖原始生成的文件
        globalConfig.setFileOverride(true);
        // 设置数据层接口名,%s为占位符,指代模块名称
        globalConfig.setMapperName("%sMapper");
        // 设置Id生成策略
        globalConfig.setIdType(IdType.ID_WORKER);
        autoGenerator.setGlobalConfig(globalConfig);

        // 设置包名
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setEntity("com.generator.entity");
        packageConfig.setMapper("com.generator.mapper");
        autoGenerator.setPackageInfo(packageConfig);

        // 策略设置
        StrategyConfig strategyConfig = new StrategyConfig();
        // 设置数据库表的前缀,模块名 = 数据库名 - 前缀名
        strategyConfig.setTablePrefix("tbl_");
        // 设置当前参与生成的表明,参数为可变参数
        strategyConfig.setInclude("tbl_product");
        // 设置是否启用Rest风格
        // strategyConfig.setRestControllerStyle(true);
        // 设置乐观锁字段名
        strategyConfig.setVersionFieldName("version");
        // 设置逻辑删除字段名
        strategyConfig.setLogicDeleteFieldName("deleted");
        // 是否启用Lombok
        strategyConfig.setEntityLombokModel(true);
        autoGenerator.setStrategy(strategyConfig);

        // 执行生成操作
        autoGenerator.execute();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值