SpringBoot入门学习笔记-14-MyBatis-Plus入门与集成

前言:

        后端连接数据库的ORM框架有很多,JPA、Mybatis都是很主流的ORM架框。但是JPA在国内使用的人越来越少了。Mybatis因为XML配置过于多,所以现在越来越流行使用mybatis-plus,号称是可以丢弃xml配置的一款ORM框架。

        mybatis-plus(以下简称MP)有很多功能,本文介绍在springboot中集成以及提供CURD的示例,更多功能可以参考官网:简介 | MyBatis-Plus (baomidou.com)https://baomidou.com/pages/24112f/

一、引入依赖。

Mybatis-Plus 依赖

maven工具构建配置POM如下:

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

gradle工具构建配置如下:

implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.5.3.1'

mysql依赖,maven配置:

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

mysql依赖,gradle配置: 

implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.33'

二、springboot配置mysql连接信息

Spring:  
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://49.234.232.xxx:3306/test?serverTimezone=GMT%2B8
    username: root
    password: xxx

配置完成以后,重启项目,能看到控制台有MP的信息未报错误就可表示成功了:

三、编写实体类和mapper

1、实体类代码。entity下面新建一个User.java类。

package com.cn.laoluobase.entity;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigInteger;
import java.sql.Types;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private BigInteger id;
    @JsonInclude(JsonInclude.Include.NON_NULL) // 当为空时不转换JSON输出。这样前端就不会返回null.
    private String userName;
    @JsonInclude(JsonInclude.Include.NON_NULL) // 当为空时不转换JSON输出。这样前端就不会返回null.
    private String roleid;
    @JsonInclude(JsonInclude.Include.NON_NULL) // 当为空时不转换JSON输出。这样前端就不会返回null.
    private Integer status;
    @JsonInclude(JsonInclude.Include.NON_NULL) // 当为空时不转换JSON输出。这样前端就不会返回null.
    private Integer isDelete;

}

2、编写@Mapper,extends baseMapper

package com.cn.laoluobase.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cn.laoluobase.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {

}

注意:@Mapper一定要写,不注入的话,后面无法@Resource

四、测试及调用示例

在Controller中调用userMapper.selectList()方法。

    @GetMapping("/list")
    public String list(){
        System.out.println("************************demo/mp/list***********************");
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println); // System.out::println =>System.out.println(user)

        return "OK";
    }

完整截图如下:

网页访问后,控制台会输出相关的记录:

 五、MP主要内置方法介绍

上面的测试示例中,我们使用了userMapper.selectList()。它继承自BaseMapper。
1、内置了很多常用方法,列表。

// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

除了select方法以外,还有insert\update\delete等。

// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

2、select 示例

package com.cn.laoluobase.controller.demo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.laoluobase.entity.User;
import com.cn.laoluobase.mapper.UserMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/demo/mp")
public class MybatisPlusDemo {
    @Resource
    private UserMapper userMapper;

    @GetMapping("/select")
    public String list1(){

        // 根据 ID 查询。查找id=54的记录
        User user = userMapper.selectById(54);
        System.out.println(user);
        // User(id=54, userName=lily, roleid=null, status=5, isDelete=0)

        // 根据 columnMap 条件。这是一种灵活的方式,但是容易写错字段名,写错字段类型
        // 比如如下查找roleid=admin,status=2为条件的记录,则只需把条件都放到map对象中即可。
        HashMap userMap =new HashMap();
        userMap.put("roleid","admin");
        userMap.put("status",2);
        List<User> userList = userMapper.selectByMap(userMap);
        userList.forEach(System.out::println); // System.out::println =>System.out.println(user)
        // User(id=50, userName=test, roleid=admin, status=2, isDelete=0)

        // 根据 Wrapper 条件,查询全部记录
        QueryWrapper<User> userQueryWrapper = new QueryWrapper();
        userQueryWrapper.like("user_name","bill");
        List<User>  userList1 = userMapper.selectList(userQueryWrapper);
        System.out.println("************************userQueryWrapper***********************");
        userList1.forEach(System.out::println); // System.out::println =>System.out.println(user)
        //User(id=51, userName=bill, roleid=admin, status=1, isDelete=0)
        return "OK";
    }
}

3、insert示例 

    @GetMapping("/insert")
    public String insert(){
        User user =new User();
        user.setUserName("laoluo");
        user.setRoleid("admin");
        Integer row = userMapper.insert(user);
        System.out.println(row);
        // 1 返回1表示影响的行数,不是ID。
        System.out.println(user);
//        User(id=1673213664939577346, userName=laoluo, roleid=admin, status=null, isDelete=null)
        return "OK";
    }

可以用接收insert的返回,表示影响的行数,不是0就表示成功。返回值会自动写到实体类中。 

4、id字段自增长,需要在实体中设置@TableId

上面inset方法中,插入的id是java产生的,不是数据库自增长的,可以设置主键自增长实现跟随数据库自增长。

 

  五、Wrapper支持很多函数,常用的除了like,还有eq,gt,lt,between,isnull,in 等。

 六、点到为止,不扩展了。

mybatis-plus本身的官方文档是中文的,写得很好。如果需要了解更多的使用,请移步到官方吧。我这里就不扩展了,仅以示例的方式做基本使用的介绍。

结束语:

项目完整源码可以到gitee下载:laoluo: Springboot、SpringCloud项目

<think>好的,我现在需要回答用户关于MyBatis-Plus Spring Boot Starter使用方法及文档的问题。用户提到在集成过程中遇到了依赖冲突和找不到绑定语句的错误,引用了三个相关的资料。 首先,我应该先理解用户的具体需求。用户想了解如何正确使用MyBatis-PlusSpring Boot Starter,可能涉及到依赖配置、基本用法以及常见问题的解决。根据用户提供的引用,问题可能出在依赖冲突,特别是mybatis-spring-boot-starter和mybatis-plus的starter之间的冲突,还有JDK版本兼容性问题。 接下来,我需要按照系统级指令来组织回答。必须使用中文,行内数学表达式用$...$,但这个问题可能不太涉及数学公式,但要注意代码块和引用格式。回答需要结构清晰,分步骤说明,并生成相关问题。同时,引用用户提供的三个参考资料,在适当的地方添加引用标识。 首先,要说明如何正确引入依赖。根据引用[2]和[3],用户可能在同时使用mybatis-spring-boot-starter和mybatis-plus的starter,导致冲突。正确的做法应该是只引入MyBatis-Plus的starter,因为它已经包含了MyBatis的核心依赖。需要给出Maven和Gradle的依赖示例,并提醒用户不要同时引入两个starter。 然后,配置部分,可能需要配置数据源、MyBatis-Plus的相关设置,比如mapper扫描路径、分页插件等。这部分需要给出application.yml或properties的示例,并说明各个配置项的作用。 基本用法部分,可以提到如何创建实体类、Mapper接口,以及使用Service CRUD接口。需要给出代码示例,比如实体类注解@TableName,Mapper继承BaseMapper,Service接口的使用等。同时,要提醒用户关于XML映射文件的位置,确保资源文件被正确扫描,避免出现找不到绑定语句的错误,如引用[1]提到的。 文档和资源部分,需要引导用户查看官方文档,特别是版本兼容性。引用[3]提到用户使用JDK22,而MyBatis-Plus的某些版本可能不支持高版本JDK,需要确认版本是否兼容。例如,建议使用3.x版本,并检查是否支持JDK22,或者可能需要升级到更新的版本。 常见问题解决部分,需要总结用户提到的依赖冲突、绑定语句找不到、JDK版本问题,并给出解决方法。例如,检查依赖树排除冲突,确认XML文件路径正确,检查JDK版本兼容性。 最后,生成相关问题,应该围绕依赖管理、配置优化、高级功能、异常处理等,帮助用户进一步解决问题。 在回答过程中,需要确保所有引用都正确标注,比如引用[1]关于错误排查,引用[2]关于依赖冲突,引用[3]关于JDK版本问题。同时,代码块要使用正确的语法高亮,比如用```xml或```java。 现在需要检查是否有遗漏的部分,比如是否提到了分页插件、自动填充等功能,这些都是MyBatis-Plus的常用特性,用户可能会感兴趣。此外,是否需要提到Spring Boot的版本兼容性,因为不同版本的Spring Boot可能需要不同版本的MyBatis-Plus Starter。 总结下来,回答的结构应该是: 1. 依赖引入 2. 基础配置 3. 基本用法(实体类、Mapper、Service) 4. 文档参考 5. 常见问题 6. 相关问题 确保每个部分都简洁明了,并引用相关的问题点。例如,在依赖引入部分强调不要同时引入MyBatisMyBatis-Plus的starter,引用[2]中的冲突情况。在配置部分提醒检查XML路径,引用[1]中的绑定错误。在常见问题中提到JDK版本,引用[3]中的问题。</think>### MyBatis-Plus Spring Boot Starter 使用方法及文档 #### 1. 依赖引入 MyBatis-Plus Spring Boot Starter 提供了开箱即用的集成能力,**需避免其他 MyBatis Starter 冲突**。 - **Maven 配置**(注意排除冲突依赖): ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.6</version> <exclusions> <exclusion> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </exclusion> </exclusions> </dependency> ``` - **Gradle 配置**: ```groovy implementation 'com.baomidou:mybatis-plus-boot-starter:3.5.6' ``` > **注意**:若同时引入 `mybatis-spring-boot-starter` 会导致类重复加载,引发冲突[^2]。 #### 2. 基础配置 在 `application.yml` 中配置数据源和 MyBatis-Plus 参数: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: 123456 mybatis-plus: configuration: map-underscore-to-camel-case: true # 字段下划线转驼峰 mapper-locations: classpath*:/mapper/**/*.xml # XML 映射文件路径 ``` > **排查绑定错误**:若出现 `Statement not found`,检查 XML 路径和接口方法名是否匹配[^1]。 #### 3. 基本用法 - **实体类定义**: ```java @TableName("user") // 指定表名 public class User { @TableId(type = IdType.AUTO) // 主键自增 private Long id; private String name; } ``` - **Mapper 接口**: ```java public interface UserMapper extends BaseMapper<User> { // 继承 BaseMapper 后自动拥有 CRUD 方法 } ``` - **Service 层**: ```java public interface UserService extends IService<User> {} @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {} ``` #### 4. 文档参考 - **官方文档**:[MyBatis-Plus 官网](https://baomidou.com/) 重点关注: - 分页插件配置 - 自动填充功能(如 `@TableField(fill = FieldFill.INSERT)`) - 逻辑删除配置 - **版本兼容性**:JDK 22 需确认 MyBatis-Plus 是否支持,建议使用 **3.5.6+** 版本[^3]。 #### 5. 常见问题解决 | 问题类型 | 解决方案 | |---------------------------|--------------------------------------------------------------------------| | 依赖冲突 | 使用 `mvn dependency:tree` 检查并排除冲突依赖 | | 找不到绑定语句 | 检查 XML 文件路径、方法名 XML ID 是否一致 | | JDK 版本不兼容 | 降级 JDK 或升级 MyBatis-Plus 到支持高版本 JDK 的发行版 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值