SpringBoot开发,如何使用mybatisplus代替mybatis?
发布于 作者:苏南大叔 来源:程序如此灵动~

刚刚宣布MyBatis
比JPA
更好一些,因为它可以直观的写sql
语句。就出现了一个MyBatis Plus
,理由是它不用写大部分的sql
语句。真心是“天道好轮回,苍天饶过谁”。本文写如何使用MyBatis Plus
代替MyBatis
。
苏南大叔的“程序如此灵动”博客,记录苏南大叔的代码编程经验总结。测试环境:win10
,openjdk@23.0.2
,IntelliJ IDEA 2024.3.4.1
,maven@3.3.2
,spring boot@2.5.4
,java@17
,mysql@5.7.26
,MyBatisPlus@3.4.3.4
。
前文回顾
因为本文的目的是使用mybatisplus
代替mybatis
。所以,这里先回顾一下springboot
里面集成mybatis
的文章步骤:
MyBatisPlus
MyBatis-Plus
提供了许多开箱即用的功能,使得我们不需要手写大部分的SQL
语句。它通过继承BaseMapper
接口和使用 ServiceImpl
类来实现常见的CRUD
操作。
所以,它的特点是:不需要手写大部分sql
语句。实现方式是:继承BaseMapper
接口和ServiceImpl
类。
pom.xml
这里新增MyBatisPlus
的依赖,删除MyBatis
的依赖。pom.xml
:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
执行mvn install
命令。
修改配置
src\main\resources\application.properties
:
spring.datasource.url=jdbc:mysql://localhost:3306/boot
spring.datasource.username=root
spring.datasource.password=root
mybatis-plus.mapper-locations=classpath*:mappers/*.xml
logging.level.com.example.demo.mapper=DEBUG
logging.level.com.baomidou.mybatisplus=DEBUG
logging.level.jdbc.sqlonly=DEBUG
从这个配置文件上,也可以看到:虽然MyBatisPlus
凸显的是少写sql
,并不是不写sql
。所以依然存在着配置:
mybatis-plus.mapper-locations=classpath*:mappers/*.xml
Entity文件
和JPA
/MyBatis
里面的Entity
文件差不多,仅有部分修改。src\main\java\com\example\demo\entity\User.java
:
package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import org.apache.ibatis.type.Alias;
@Alias("User")
public class User {
@TableId(type = IdType.AUTO)
private Integer id; // Ensure the ID field is Integer
private String name;
private String password;
// Getters and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
Mapper文件
在MyBatis
中,mapper
文件可是个非常重要的文件。然而,到了MyBatisPlus
里面,它的存在感一再拉低。
src\main\java\com\example\demo\mapper\UserMapper.java
:
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// No additional methods needed, BaseMapper provides CRUD operations
}
Service文件
整体上来说,和以前的版本差不多。但是它继承了MyBatisPlus
的ServiceImpl
。src\main\java\com\example\demo\service\UserService.java
:
package com.example.demo.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.User;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
public List<User> getAllUsers() {
return list();
}
public User getUserById(Integer id) {
if (id == null || id <= 0) {
throw new IllegalArgumentException("ID不能为空且必须为正数");
}
return getById(id);
}
public User getUserByName(String name) {
return lambdaQuery().eq(User::getName, name).one();
}
public User createUser(User user) {
if (user == null || user.getName() == null || user.getName().trim().isEmpty() ||
user.getPassword() == null || user.getPassword().trim().isEmpty()) {
throw new IllegalArgumentException("用户名和密码不能为空");
}
if (lambdaQuery().eq(User::getName, user.getName()).count() > 0) {
throw new RuntimeException("User with the same name already exists");
}
save(user);
return user;
}
public User updateUser(Integer id, User user) {
if (id == null || id <= 0 || user == null || user.getName() == null || user.getName().trim().isEmpty() ||
user.getPassword() == null || user.getPassword().trim().isEmpty()) {
throw new IllegalArgumentException("ID、用户名和密码不能为空且ID必须为正数");
}
User existingUser = getById(id);
if (existingUser != null) {
if (lambdaQuery().eq(User::getName, user.getName()).ne(User::getId, id).count() > 0) {
throw new RuntimeException("User with the same name already exists");
}
existingUser.setName(user.getName());
existingUser.setPassword(user.getPassword());
updateById(existingUser);
return existingUser;
}
return null;
}
public void deleteUser(Integer id) {
if (id == null || id <= 0) {
throw new IllegalArgumentException("ID不能为空且必须为正数");
}
if (count() <= 1) {
throw new RuntimeException("Cannot delete the last user");
}
removeById(id);
}
}
Controller文件
基本上没有变化,如果Service
文件提供的方法有变化的话,这里才需要变化。
结语
基本上SpringBoot
系列快速入门的文章,就这么多了。其它的就是碰到啥写啥了。jpa
、mybatis
、mybatisplus
这三个组件来看,功用基本上差不多,使用方法略有区别。但是套路上来说也都差不多。所以,选择哪一个,并不是说是必须的。根据个人喜好或者项目需求来选择即可。
更多苏南大叔的java
相关文章,请点击:


