SpringBoot整合MybatisPlus

1. 首先引入maven依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.28</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.2</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>

2. 添加数据库配置信息 application.properties

MyBatisPlus支持如下数据库:

mysql 、mariadb 、oracle 、db2、 h2、 hsql 、sqlite 、postgresql 、sqlserver

达梦数据库 虚谷数据库 人大金仓数据库

spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus-demo
spring.datasource.username = root
spring.datasource.password = root

# 打印执行sql
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3. 启动类添加扫描Mapper文件的注解

@MapperScan("com.demo.*.mapper")

 4. 接口需要继承 BaseMapper 泛型传入实体类

public interface DemoMapper extends BaseMapper<Demo> {}

5. 测试查询 xml都不用写

@SpringBootTest
class MybatisPlusDemoTests {
    @Autowired
    private DemoMapper demoMapper;

    @Test
    public void testSelect() {
         // wrapper.like("name",666);
        // 大于等于ge("name",100)
        // 自定义 apply("name like {0} and age>={1}","%张%",18);
        // 只返回id和name两个字段wrapper.select("id","name");
        // 查询所有数据
        List<User> list = demoMapper.selectList(null);
        list.forEach(System.out::println);
    }


    @Test
    public void testInsert() {
        User= new User(null,2,3)
        int rs = demoMapper.insert(demo);
        System.out.println("成功插入条数:"+rs+"插入的主键id:"+demo.getId());
    }


    @Test
    public void testUpdateById() {
        // 只修改不为空的字段
        int rs = demoMapper.updateById(new User(1,7,8));
        System.out.println("修改成功的条数:"+ rs);
    }

    
    @Test
    public void testUpdateQueryCondition() {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        // 根据条件更新
        wrapper.eq("name",7);
        int rs = demoMapper.update(new User(null,7,8),wrapper);
        System.out.println("修改成功的条数:"+ rs);
    }

    @Test
    public void testDeleteById() {
        // 根据id删除
        int rs = demoMapper.deleteById(1);
        System.out.println("删除成功的条数:"+ rs);
    }

    @Test
    public void testDeleteQueryCondition() {
        // 根据name删除 还可以批量删除 deleteBatchIds(Collection<?> idList);
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("name",1);
        int rs = userMapper.delete(wrapper);
        System.out.println("删除成功的条数:"+ rs);
    }


    @Test
    public void testQueryWrapper1() {
        // 使用LambdaQueryWrapper实现类可以使用lambda表达式
        // LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        LambdaQueryWrapper<User> wrapper = new QueryWrapper().lambda();
        wrapper.like(User::getName,1);
        List<User> demoList = demoMapper.selectList(wrapper);
        demoList.forEach(System.out::println);
    }


    @Test
    public void testQueryWrapper6() {
        // 指定要查询的字段
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.select(User::getId,User::getName);
        wrapper.like(User::getName,"张");
        List<User> userList = userMapper.selectList(wrapper);
        userList.forEach(System.out::println);
    }


    @Test
    public void testQueryWrapper7() {
        // condition动态条件拼接
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        String name = "张";
        wrapper.like(name != null,User::getName,"张");
        List<User> userList = userMapper.selectList(wrapper);
        userList.forEach(System.out::println);
    }

    @Test
    public void testQueryWrapper8() {
        // 链式拼接条件
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.select(User::getId,User::getName);
        wrapper.like(User::getName,"张").eq(User::getEmail,"aa@qq.com");
        List<User> userList = userMapper.selectList(wrapper);
        userList.forEach(System.out::println);
    }

}

6. 分页查询

 先增加配置类

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {


    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


    // 旧版
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
//        // paginationInterceptor.setOverflow(false);
//        // 设置最大单页限制数量,默认 500 条,-1 不受限制
//        // paginationInterceptor.setLimit(500);
//        // 开启 count 的 join 优化,只针对部分 left join
//        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
//        return paginationInterceptor;
//    }

}

@Test
public void testSelectPage() {
    // 这里会执行两次的SQL,先查询符合条件的总记录数,再通过limit查询出分页数据。
    QueryWrapper<User> wrapper = new QueryWrapper();
    IPage<User> page = new Page<>(2,3);
    page  = userMapper.selectPage(page,wrapper);
    long total =  page.getTotal();//总条数
    long pageNum = page.getCurrent();//当前页码
    long pageSize = page.getSize();//每页显示条数
    List<User> records = page.getRecords();//记录数据
    System.out.println("total:"+total+",pageNum:"+pageNum+",pageSize:"+pageSize);
}

7.Service接口继承IService

定义一个接口如UserService,继承接口IService<T>

import com.baomidou.mybatisplus.extension.service.IService;
import com.kfit.user.model.User;

public interface UserService extends IService<User> {

}

8.Service实现类继承ServiceImpl

定义服务接口UserService的实现类UserServiceImpl,并且继承实现类ServiceImpl

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kfit.user.mapper.UserMapper;
import com.kfit.user.model.User;
import com.kfit.user.service.UserService;
import org.springframework.stereotype.Service;

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

}

9. 注解

@TableName("sys_user") //表名注解,标识实体类对应的表

属性

类型

必须指定

默认值

描述

value

String

""

表名

schema

String

""

schema

keepGlobalPrefix

boolean

false

是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时)

resultMap

String

""

xml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定)

autoResultMap

boolean

false

是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建与注入)

excludeProperty

String[]

{}

需要排除的属性名 @since 3.3.1

关于 autoResultMap 的说明:

MP 会自动构建一个 resultMap 并注入到 MyBatis 里(一般用不上),请注意以下内容:

因为 MP 底层是 MyBatis,所以 MP 只是帮您注入了常用 CRUD 到 MyBatis 里,注入之前是动态的(根据您的 Entity 字段以及注解变化而变化),但是注入之后是静态的(等于 XML 配置中的内容)。

而对于 typeHandler 属性,MyBatis 只支持写在 2 个地方:

(1)定义在 resultMap 里,作用于查询结果的封装

(2)定义在 insert 和 update 语句的 #{property} 中的 property 后面(例:#{property,typehandler=xxx.xxx.xxx}),并且只作用于当前 设置值

除了以上两种直接指定 typeHandler 的形式,MyBatis 有一个全局扫描自定义 typeHandler 包的配置,原理是根据您的 property 类型去找其对应的 typeHandler 并使用。

@TableId(type = IdType.AUTO) // 字段主键注解

属性

类型

必须指定

默认值

描述

value

String

""

主键字段名

type

Enum

IdType.NONE

指定主键类型

IdType枚举值:

描述

AUTO

数据库 ID 自增

NONE

无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)

INPUT

insert 前自行 set 主键值

ASSIGN_ID

分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)

ASSIGN_UUID

分配 UUID,主键类型为 String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认 default 方法)

ID_WORKER

分布式全局唯一 ID 长整型类型(please use ASSIGN_ID)

UUID

32 位 UUID 字符串(please use ASSIGN_UUID)

ID_WORKER_STR

分布式全局唯一 ID 字符串类型(please use ASSIGN_ID)

@TableField // 字段注解(非主键)

属性

类型

必须指定

默认值

描述

value

String

""

数据库字段名

exist

boolean

true

是否为数据库表字段

condition

String

""

字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s},参考(opens new window)

update

String

""

字段 update set 部分注入,例如:当在version字段上注解update="%s+1" 表示更新时会 set version=version+1 (该属性优先级高于 el 属性)

insertStrategy

Enum

FieldStrategy.DEFAULT

举例:NOT_NULL
insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null">#{columnProperty}</if>)

updateStrategy

Enum

FieldStrategy.DEFAULT

举例:IGNORED
update table_a set column=#{columnProperty}

whereStrategy

Enum

FieldStrategy.DEFAULT

举例:NOT_EMPTY
where <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>

fill

Enum

FieldFill.DEFAULT

字段自动填充策略

select

boolean

true

是否进行 select 查询

keepGlobalFormat

boolean

false

是否保持使用全局的 format 进行处理

jdbcType

JdbcType

JdbcType.UNDEFINED

JDBC 类型 (该默认值不代表会按照该值生效)

typeHandler

Class<? extends TypeHandler>

UnknownTypeHandler.class

类型处理器 (该默认值不代表会按照该值生效)

numericScale

String

""

指定小数点后保留的位数

关于`jdbcType`和`typeHandler`以及`numericScale`的说明:

numericScale只生效于 update 的 sql. jdbcType和typeHandler如果不配合@TableName#autoResultMap = true一起使用,也只生效于 update 的 sql. 对于typeHandler如果你的字段类型和 set 进去的类型为equals关系,则只需要让你的typeHandler让 Mybatis 加载到即可,不需要使用注解

FieldStrategy

描述

IGNORED

忽略判断

NOT_NULL

非 NULL 判断

NOT_EMPTY

非空判断(只对字符串类型字段,其他类型字段依然为非 NULL 判断)

DEFAULT

追随全局配置

NEVER

不加入SQL

FieldFill

描述

DEFAULT

默认不处理

INSERT

插入时填充字段

UPDATE

更新时填充字段

INSERT_UPDATE

插入和更新时填充字段

@Version // 乐观锁注解
@TableLogic // 表字段逻辑处理注解(逻辑删除)

属性

类型

必须指定

默认值

描述

value

String

""

逻辑未删除值

delval

String

""

逻辑删除值

@OrderBy // 内置 SQL 默认指定排序,优先级低于 wrapper 条件查询

属性

类型

必须指定

默认值

描述

isDesc

boolean

true

是否倒序查询

sort

short

Short.MAX_VALUE

数字越小越靠前

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今晚哒老虎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值