SpringBoot整合MybatisPlus教程

发布于:2023-01-16 ⋅ 阅读:(186) ⋅ 点赞:(0)

1.概述

​ MybatisPlus是一款Mybatis增强工具,用于简化开发,提高效率。 它在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

​ 官网: https://mp.baomidou.com/

2.快速入门

2.0 准备工作

①准备数据

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `user_name` varchar(20) NOT NULL COMMENT '用户名',
  `password` varchar(20) NOT NULL COMMENT '密码',
  `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  `address` varchar(100) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`user_name`,`password`,`name`,`age`,`address`) values (1,'ruiwen','123','瑞文',12,'山东'),(2,'gailun','1332','盖伦',13,'平顶山'),(3,'timu','123','提姆',22,'蘑菇石'),(4,'daji','1222','妲己',221,'狐山');

②创建SpringBoot工程

添加依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

创建启动类

@SpringBootApplication
public class MybatisPlusApplication {

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

③准备实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String address;
}

2.1 使用MybatisPlus

①添加依赖

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

②配置application.yml文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: delFlag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
      #表名前缀
#      table-prefix: tb_
      #主键自动增长
      id-type: auto
      #关闭驼峰命名策略
#  configuration:
#    map-underscore-to-camel-case: false
      #日志设置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #mybatis自定义sql
  mapper-locations: classpath*:/mapper/**/*.xml #mapper文件夹放在resources下面
server:
  port: 8080

③创建Mapper接口

创建Mapper接口继承BaseMapper接口

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

BaseMapper接口中已经提供了很多常用方法。所以我们只需要直接从容器中获取Mapper就可以进行操作了,不需要自己去编写Sql语句。

④配置Mapper扫描

在启动类上配置我们的Mapper在哪个包。

@SpringBootApplication
@MapperScan("com.springboot.mapper")
public class MybatisPlusApplication {

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

⑤获取Mapper进行测试

@SpringBootTest
public class MPTest {

    @Autowired
    private UserMapper userMapper;

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

service接口

@Service
public interface UserService extends IService<User> {

}

servicelmpl实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

}

MybatisPlus配置类

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

    /**
     *  mybatis-plus 插件的配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    /**
     * Id 生成器-->
     * 特殊的一些类使用
     * 默认使用
     * @return
     */
    @Bean
    public IKeyGenerator iKeyGenerator(){
        return new H2KeyGenerator();
    }

}

MybatisPlus分页

    @GetMapping("/page")
    public Page<AssExpertManage> page(Long pageNum, Long pageSize) {
        Page<AssExpertManage> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AssExpertManage> lambda = new LambdaQueryWrapper<>();
        return assExpertManageMapper.selectPage(page, lambda);
    }

MybatisPlus新增更新

   @PostMapping("/insertUpdate")
    public String insertUpdate(@RequestBody AssExpertManage assExpertManage) {
        if (ObjectUtils.isNotEmpty(assExpertManage.getId())) {
            assExpertManage.setId(assExpertManage.getId());
            assExpertManageMapper.updateById(assExpertManage);
            return "更新成功";
        }
        AssExpertManage assExpertManage1 = new AssExpertManage();
        assExpertManage1.setExpertName(assExpertManage.getExpertName());
        assExpertManageMapper.insert(assExpertManage1);
        return "新增成功";
    }

自动填充创建、更新时间


@TableField(fill = FieldFill.INSERT)
private Date createTime;  //create_time

@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime; //update_time

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //mp执行添加操作,这个方法执行
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //mp执行修改操作,这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到