Springboot将mybatis替换为mybatis-plus

知识点:

1、Mybatis-plus相比mybatis,功能更加强大,简而言之,不需要我们去写mapper.xml配置,但是对于特殊需求的sql语句,还是需要写mapper.xml文件中的sql语句。
  也增加了很多注解,让我们减少了开发的一些繁琐的操作。
  mybatis-plus和和lombok一起使用,你会发现很完美
2、使用pageHelper插件进行分页查询

下面开始工程改造

1、注释以前的mybatis注解(我试了下不去注解,会报错),也可以不注释掉,注意看使用的mybatis-plus的包,我使用的是3.11版本必须注释,但是这个版本不需要

注释:mybatis-spring-boot-starter

2、添加mybatis-plus注解

添加:(可以查看官网的案例:https://mp.baomidou.com/guide/quick-start.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B)
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>

3、配置文件

1、配置不需要改动,保留mybatis的配置,但在application.yml文件中添加:
  url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8
  修改自己的库名。
2、将原有的mybatis改为mybatis-plus
  mybatis-plus:
  typeAliasesPackage: com.cn.commodity.entity
  mapperLocations: classpath:mapper/*.xml
注意:本人电脑必须要加serverTimezone=GMT%2B8,否则报时区错误

4、mybatis-plus找表名

由于mybatis对mapper.xml中表名进行映射,可以找到数据库中的表名,
但是mybatis-plus使用内置的方法时,如(List<User> userList =  userDao.selectList(null);),
需要在实体对象中加注解,如(@TableName(value = "user_t"))
这样,mybatis-plus就能找到数据库和实体对象的映射关系。

5、对Dao类继承BaseMapper

public interface UserDao extends BaseMapper<User> {}

这样就可以将mybatis改造为mybatis-plus工程,亲测有效

如果有问题,自己也可以查看官网:https://mp.baomidou.com/guide/quick-start.html#%E7%BC%96%E7%A0%81
还有很多注解,可以使用

@TableName(value = "user_t")
@TableId(value = "id",type = IdType.AUTO)
@TableField(value = "user_name")

 #############上面配置mybatis-plus,下面配置pageHelper互不影响#################

6、添加pageHelper依赖

 <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
</dependency>

7、使用pageHelper案例

 @RequestMapping("/mybatisPlus")
    @ResponseBody
    public  PageInfo<User> mybatisPlus(HttpServletRequest request){
        PageHelper.startPage(1,10);
           List<User> userList =  userDao.selectList(null);
        PageInfo<User> pageInfo = new PageInfo(userList);
        System.out.println(userList);
        return pageInfo;
    }

 

注意事项:

  本人在配置mybatis-plus和pageHelper的时候,发现很多错误,都是版本兼容问题。

 

posted @ 2019-06-20 11:35  小白啊小白,Fighting  阅读(18704)  评论(0编辑  收藏  举报