配置Mybatis-plus

1 引入相关依赖

 1 <!--mybatis-plus-->
 2 <dependency>
 3      <groupId>com.baomidou</groupId>
 4      <artifactId>mybatis-plus-boot-starter</artifactId>
 5      <version>3.0.5</version>
 6 </dependency>
 7 <!--mysql-->
 8 <dependency>
 9      <groupId>mysql</groupId>
10      <artifactId>mysql-connector-java</artifactId>
11 </dependency>
  <dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity</artifactId>
  <version>1.7</version>
</dependency>
  <dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity-tools</artifactId>
  <version>2.0</version>
  </dependency>
 

 

2 application.property配置文件中配置数据库相关的配置信息

1 #mysql数据库连接
2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3 spring.datasource.url=jdbc:mysql://localhost:3306/数据库名
4 spring.datasource.username=用户名
5 spring.datasource.password=密码

  配置数据库连接配置的注意点:

mysql8以上(spring boot 2.1)
注意:driver和url的变化
 
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456


注意:
1、这里的 url 使用了 ?serverTimezone=GMT%2B8 后缀,因为Spring Boot 2.1 集成了 8.0版本的jdbc驱动,这个版本的 jdbc 驱动需要添加这个后缀,否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more 
2、这里的 driver-class-name 使用了  com.mysql.cj.jdbc.Driver ,在 jdbc 8 中 建议使用这个驱动,之前的 com.mysql.jdbc.Driver 已经被废弃,否则运行测试用例的时候会有 WARN 信息

 

 

3 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹   

  ----->(这一步应该是配合使用第三方框架时加入的扫描mapper, 一般情况下都会使用到这个东西, 所以建立spring boot的时候就会把这个注解加上去)

  注意:扫描的包名根据实际情况修改

 

1 @SpringBootApplication
2 @MapperScan("com.atguigu.mybatisplus.mapper")
3 public class SelfApplication {
4     ......
5 }

 

 

 

 

4 创建实体类entity  (由于我们是对数据库进行访问操作, 我们建立的entity实体属性应该是与数据库中的字段具有对应关系)

  对实体类的属性进行的操作:  

  (1) 配置主键生成策略:(总共有5中策略, 分析IdType源码可知, 我好想比较喜欢用全局唯一ID)

1 @TableId(type = IdType.ID_WORKER)
2 private Long id;

 

  (2) 配置自动填充属性(字段)[例如: 创建时间, 更新时间]------->这里需要注意的是, entity属性名与数据库字段名要有对应关系(可以通过注解使其对应)

  操作对象上加上相应注解

1 @TableField(fill = FieldFill.INSERT)
2 private Date createTime;
3 4 @TableField(fill = FieldFill.INSERT_UPDATE)
5 private Date updateTime;

 

  实现元对象处理器接口(不要忘记加@Component注解)

 1 @Component
 2 public class MyMetaObjectHandler implements MetaObjectHandler {
 3  4     @Override
 5     public void insertFill(MetaObject metaObject) {
 6        
 7         this.setFieldValByName("createTime", new Date(), metaObject);
 8         this.setFieldValByName("updateTime", new Date(), metaObject);
 9     }
10 11     @Override
12     public void updateFill(MetaObject metaObject) {
13      
14         this.setFieldValByName("updateTime", new Date(), metaObject);
15     }
16 }

 

 

5 配置mapper

  (1) 首先创建mapper包,

  (2) 自定义mapper接口继承框架提供的BaseMapper<>接口,   (一般情况下的原则是一个mapper接口对应一个数据库表对应一个实体类entity)

  (3) 注意, 这个位置, 需要在mapper处添加一个@Repository注解以方便被程序扫描到

@Repository
public
interface EntityMapper extends BaseMapper<Entity> { .......... }

 

  (4) 在需要使用到此mapper的地方直接引入即可(一般情况下, 都是在相对应的service中引入, 我们在controller中引入的一般是service接口)

 1 public class CRUDTests {
 2  3     @Autowired
 4     private UserMapper userMapper;
 5  6     @Test
 7     public void testInsert(){
 8  9         User user = new User();
10         user.setName("Helen");
11         user.setAge(18);
12         user.setEmail("55317332@qq.com");
13 14         int result = userMapper.insert(user);
15         System.out.println(result); //影响的行数
16         System.out.println(user); //id自动回填
17     }
18 }

 

  

6 配置乐观锁

乐观锁实现方式:
1 取出记录时,获取当前version 2 更新时,带上这个version 3 执行更新时, set version = newVersion where version = oldVersion 4 如果version不对,就更新失败

 (1) 数据库添加version字段

  ALTER TABLE `user` ADD COLUMN `version` INT

 

 (2) 实体类添加version属性, 并配置上@Version注解

1 @Version
2 @TableField(fill = FieldFill.INSERT)
3 private Integer version;

 (3) 元对象处理器接口添加version的insert默认值

1 @Override
2 public void insertFill(MetaObject metaObject) {
3     ......
4     this.setFieldValByName("version", 1, metaObject);
5 }

 7 配置MybatisPlusConfig配置类

 1 @EnableTransactionManagement
 2 @Configuration
 3 @MapperScan("com.atguigu.mybatis_plus.mapper")/*此时可以删除主类中的@MapperScan注解了*/
 4 public class MybatisPlusConfig {
 5  6     /**
 7      * 乐观锁插件
 8      */
 9     @Bean
10     public OptimisticLockerInterceptor optimisticLockerInterceptor() {
11         return new OptimisticLockerInterceptor();
12     }
13  
14     /**
15      * 分页插件
16      */
17     @Bean
18     public PaginationInterceptor paginationInterceptor() {
19         return new PaginationInterceptor();
20     }
21 
22     /**
23      * 逻辑删除Bean
24      */
25     @Bean
26     public ISqlInjector sqlInjector() {
27     return new LogicSqlInjector();
28     }
29 
30 }

 

8 配置逻辑删除

1 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除数据
2 
3 逻辑删除:假删除,将对应数据中代表是否被删除字段状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录

  (1) 数据库中添加deleted字段

  ALTER TABLE `user` ADD COLUMN `deleted` boolean

   (2) 实体类添加deleted字段 并 配置@TableLogic注解和@TableField(fill = FieldFill.INSERT)注解

1 @TableLogic
2 @TableField(fill = FieldFill.INSERT)
3 private Integer deleted;

  (3) 元对象处理器接口添加deleted的insert默认值

1 @Override
2 public void insertFill(MetaObject metaObject) {
3     ......
4     this.setFieldValByName("deleted", 0, metaObject);
5 }

  (4) application.properties主配置文件中加入相关配置

1 此为默认值,如果你的默认值和mp默认的一样,该配置可无
2  
3 mybatis-plus.global-config.db-config.logic-delete-value=1
4 mybatis-plus.global-config.db-config.logic-not-delete-value=0

  (5) 在MybatisPlusConfig中注册逻辑注入的Bean

1 @Bean
2 public ISqlInjector sqlInjector() {
3     return new LogicSqlInjector();
4 }

 

9 配置分页查询

  (1) MyBatisPlusConfig中配置分页插件Bean

1 /**
2  * 分页插件, (只需要简单配置就可以直接使用了)
3  */
4 @Bean
5 public PaginationInterceptor paginationInterceptor() {
6     return new PaginationInterceptor();
7 }

   (2) 熟悉基本使用方法

这个只是示范使用, 具体使用查看官网教程

@ApiOperation(value = "分页讲师列表")
@GetMapping("{page}/{limit}")
public Result pageList(
        @ApiParam(name = "page", value = "当前页码", required = true)
        @PathVariable Long page,

        @ApiParam(name = "limit", value = "每页记录数", required = true)
        @PathVariable Long limit){

    Page<EduTeacher> pageParam = new Page<>(page, limit);

    eduTeacherService.page(pageParam, null);
    List<EduTeacher> records = pageParam.getRecords();
    long total = pageParam.getTotal();

    return  Result.ok().data("total", total).data("rows", records);
}

 

posted @ 2021-01-09 01:20  0龙行者0  阅读(126)  评论(0编辑  收藏  举报