本篇文章,我们讲一下如何去使用苞米豆的Mybatis Plus来进行数据库访问
1、添加Mybatis依赖
首先要添加对应的依赖:
Spring Boot 3.5.0 、Mybatis Plus 版本是 3.5.12、MySQL数据库驱动版本是 8.2.0、Mybatis-Spring 版本是 3.0.3(至少我这么配暂时能跑起来)
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.5.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.12</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.2.0</version> </dependency>
2、添加数据源配置文件
新建一个配置文件,比如我这个是 application-db-test.yml (连线信息修改成自己的)
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root url: jdbc:mysql://127.0.0.1:3306/db_test?&serverTimezone=Asia/Shanghai
在主配置中,在include中添加 db-test 这一项
spring: application: name: MyFirstProject profiles: active: test include: test1,test2,db-test #在这里哦
3、创建数据表并添加测试数据
首先我们创建一个 userinfo 表 ,里面包含了 uid(作为主键)、name、age
CREATE TABLE `userinfo`( `uid` INT NOT NULL AUTO_INCREMENT COMMENT '用户id', `name` VARCHAR(50) NOT NULL, `age` INT NOT NULL PRIMARY KEY (`uid`) );
再插入一些测试数据
INSERT INTO userinfo (`name`,`age`) VALUES ('小明',8);
INSERT INTO userinfo (`name`,`age`) VALUES ('小红',5);4、创建实体类
目前我是把数据和业务层单独抽离了出来,其实就是创建一个新的组件用来放入口和控制器,然后把根目录下src里面的内容移动到新组建里面启动配置改一下就行,后期抽空再写一篇关于这个的~
这个是 UserInfo 实体类的代码
package xyz.ygmx.test.business.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("username")
public class UserInfo {
@TableId(value = "uid", type=IdType.AUTO)//这个是设置标识列,并且自增
@TableField("uid")//绑定对应的列名
private int uid;
@TableField("name")
private String name;
@TableField("age")
private int age;
}5、创建映射(Mapper)
创建一个接口,名称设定为 UserInfoMapper 然后要继承 BaseMapper 这个类
代码如下(对的没错,简单查询的话暂时什么都不用写,Mybatis plus 自带的增删改查):
这里有个坑,SpringBoot 可能扫描不到 Mapper,可以在程序的入口类添加 @SpringBootApplication(scanBasePackages = {"xyz.ygmx.test"}) 注解解决此问题,这个是设定了扫描的范围(包名改成自己的)
package xyz.ygmx.test.business.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import xyz.ygmx.test.business.user.entity.UserInfo;
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}在这个项目的 resource 目录下建立一个 mapper 目录,里面再建立一个 user 目录,这个就是放和用户有关所有数据表映射的~
里面的内容是这样~ (如果没有自定sql语句的话可以先不建立)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--指定Mapper接口的位置--> <mapper namespace="xyz.ygmx.test.business.user.mapper.UserInfoMapper"> </mapper>
6、进行查询
创建对应的Service接口和实现类(具体类怎么放看个人喜好,我反正比较喜欢把实现的类用一个impl包装起来)
接口中继承 IService<UserInfo>接口,实现类中继承 ServiceImpl<UserInfoMapper,UserInfo>
(这个泛型写这个Service主要操作的实体就好,其余的Mapper可以通过依赖注入后拿到)
并且,实现类要用 @Service 这个注解修饰,不然注入会报错的哦~
我们在 Service 的实现类里面(我的是 IUserInfoService),添加一个方法,写入如下的测试代码,感受一下条件查询~
@Autowired //直接把实例注入
private UserInfoMapper userInfoMapper;
//按名字查询
public UserInfo getByName(String name){
// //这个是注入Mapper的写法
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
// queryWrapper.lambda().like(UserInfo::getName, name).last("LIMIT 1");//查询中名字包含xxx的,就像sql中 like '%xxx%',可能返回多个数据,所以限制为1个
// UserInfo u = null;
// u=userInfoMapper.selectOne(queryWrapper);
//这个是直接用Mybatis Plus自带的查询
UserInfo u = null;
u=this.lambdaQuery().like(UserInfo::getName,name).last("LIMIT 1").one();//查询中名字包含xxx的,就像sql中 like '%xxx%',可能返回多个数据,所以限制为1个
if(u==null){
u=new UserInfo();
u.setName("不存在的");
u.setUid(-1);
u.setAge(200);
}
return u;
}当然,插入新数据也是可以的~(别杠!我这个只是为了方便一下理解,正常开发这个得用返回对象封装的)
@Autowired //直接把实例注入
private UserInfoMapper userInfoMapper;//前面添加过这个Mappeer就不用管了~
//添加数据(Mapper中的方法)
public int createUserByMapper(UserInfo userInfo){
int res=userInfoMapper.insert(userInfo);//使用Mapper新增数据(返回执行行数,个人比较推荐)
return res;
}
//添加数据(MybatisPlus 自带方法)
public boolean createUser(UserInfo userInfo){
boolean res=this.save(userInfo);
return res;
}还有删除和修改哦~
//修改对应uid的用户名(Mapper中的方法)
public boolean editUserByPlus(int uid,String newName){
//这里面有个坑,如果age你没有设置,默认是0,结果咱们在更新name的时候也把age改成0了
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("uid",uid);
// UserInfo userInfo = new UserInfo();
// userInfo.setName(newName);
UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("uid",uid).set("name",newName);
return this.update(updateWrapper);
}
//修改对应uid的用户名(Mapper中的方法)
public int editUserByMapper(int uid,String newName){
//这里面有个坑,如果age你没有设置,默认是0,结果咱们在更新name的时候也把age改成0了
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("uid",uid);
// UserInfo userInfo = new UserInfo();
// userInfo.setName(newName);
UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("uid",uid).set("name",newName);
return userInfoMapper.update(updateWrapper);
}注意:实现方法建立完成后还不能直接引用,要在它的接口中(我的是 IUserInfoService )暴露一下的哦,像这样~
//条件查询 UserInfo getByName(String name); //添加数据(Mapper中的方法) int createUserByMapper(UserInfo userInfo); //添加数据(MybatisPlus 自带方法) boolean createUser(UserInfo userInfo); //修改对应uid的用户名(Mapper中的方法) boolean editUserByPlus(int uid,String newName); //修改对应uid的用户名(Mapper中的方法) int editUserByMapper(int uid,String newName); //删除对应uid的用户(MybatisPlus 自带方法) boolean deleteUserByPlus(int uid); //删除对应uid的用户(Mapper中的方法) int deleteUserByMapper(int uid);
前面做好后,就可以在Controller里面写啦,注意要使用 @Autowried 修饰 Service 来实现手动注入的哦~
@Autowired private IUserService userService;
然后写调用的方法~
//通过名字查询用户
@GetMapping("getuserbyname/{username}")
public UserInfo getUserByName(@PathVariable String username){
UserInfo ui = userService.getByName(username);
return ui;
}
//这个是通过Mapper创建的用户
@GetMapping("createuserbymapper")
public int createUser_1(UserInfo userInfo){
int res=userService.createUserByMapper(userInfo);
return res;
}
//通过 MybatisPlus 自带的方法创建用户
@GetMapping("createuserbyplus")
public boolean createUser_2(UserInfo userInfo){
boolean res=userService.createUser(userInfo);
return res;
}直接启动!(目前展示了新增和查询,其余的大差不差,都可以自行尝试~)
这个是查询用户的运行结果
user/getuserbyname/小红

这个是通过 Mapper 添加用户的执行结果
user/createuserbymapper?name=通过 Mapper 创建的用户&age=20

这个是通过Mybatis Plus自带方法添加用户的执行结果
user/createuserbyplus?name=通过Mybatis%20Plus%20创建的用户&age=20

到数据库查一下,完美~

3、全部代码
UserInfo.java
package xyz.ygmx.test.user.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
//import lombok.Data;
//@Data
@TableName("userinfo")
public class UserInfo {
@TableId(value = "uid", type=IdType.AUTO)//这个是设置标识列,并且自增
@TableField("uid")//绑定对应的列名
private int uid;
@TableField("name")
private String name;
@TableField("age")
private int age;
public void setUid(int uid) {
this.uid = uid;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getUid(){
return uid;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}UserInfoMapper.java
package xyz.ygmx.test.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xyz.ygmx.test.user.entity.UserInfo;
@Mapper
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}IUserService.java
package xyz.ygmx.test.user.services;
import xyz.ygmx.test.user.entity.UserInfo;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IUserService extends IService<UserInfo> {
//条件查询
UserInfo getByName(String name);
//添加数据(Mapper中的方法)
int createUserByMapper(UserInfo userInfo);
//添加数据(MybatisPlus 自带方法)
boolean createUser(UserInfo userInfo);
//修改对应uid的用户名(Mapper中的方法)
boolean editUserByPlus(int uid,String newName);
//修改对应uid的用户名(Mapper中的方法)
int editUserByMapper(int uid,String newName);
//删除对应uid的用户(MybatisPlus 自带方法)
boolean deleteUserByPlus(int uid);
//删除对应uid的用户(Mapper中的方法)
int deleteUserByMapper(int uid);
}UserService.java
package xyz.ygmx.test.user.services.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.ygmx.test.user.entity.UserInfo;
import xyz.ygmx.test.user.mapper.UserInfoMapper;
import xyz.ygmx.test.user.services.IUserService;
@Service//必须有这个注解哦,不然无法用Autowried注入的~~
public class UserService extends ServiceImpl<UserInfoMapper,UserInfo> implements IUserService {
@Autowired //直接把实例注入
private UserInfoMapper userInfoMapper;
//修改对应uid的用户名(Mapper中的方法)
public boolean editUserByPlus(int uid,String newName){
//这里面有个坑,如果age你没有设置,默认是0,结果咱们在更新name的时候也把age改成0了
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("uid",uid);
// UserInfo userInfo = new UserInfo();
// userInfo.setName(newName);
UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("uid",uid).set("name",newName);
return this.update(updateWrapper);
}
//修改对应uid的用户名(Mapper中的方法)
public int editUserByMapper(int uid,String newName){
//这里面有个坑,如果age你没有设置,默认是0,结果咱们在更新name的时候也把age改成0了
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("uid",uid);
// UserInfo userInfo = new UserInfo();
// userInfo.setName(newName);
UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("uid",uid).set("name",newName);
return userInfoMapper.update(updateWrapper);
}
//删除对应uid的用户(MybatisPlus 自带方法)
public boolean deleteUserByPlus(int uid){
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("uid",uid);
return this.remove(queryWrapper);
}
//删除对应uid的用户(Mapper中的方法)
public int deleteUserByMapper(int uid){
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("uid",uid);
return userInfoMapper.delete(queryWrapper);
}
//添加数据(Mapper中的方法)
public int createUserByMapper(UserInfo userInfo){
int res=userInfoMapper.insert(userInfo);//使用Mapper新增数据(返回执行行数,个人比较推荐)
return res;
}
//添加数据(MybatisPlus 自带方法)
public boolean createUser(UserInfo userInfo){
boolean res=this.save(userInfo);
return res;
}
//按名字查询
public UserInfo getByName(String name){
// //这个是注入Mapper的写法
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
// queryWrapper.lambda().like(UserInfo::getName, name).last("LIMIT 1");//查询中名字包含xxx的,就像sql中 like '%xxx%'
// UserInfo u = null;
// u=userInfoMapper.selectOne(queryWrapper);
//这个是直接用Mybatis Plus自带的查询
UserInfo u = null;
u=this.lambdaQuery().like(UserInfo::getName,name).last("LIMIT 1").one();//查询中名字包含xxx的,就像sql中 like '%xxx%',可能返回多个数据,所以限制为1个
if(u==null){
u=new UserInfo();
u.setName("不存在的");
u.setUid(-1);
u.setAge(200);
}
return u;
}
}UserController.java
package xyz.ygmx.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
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 xyz.ygmx.test.user.entity.UserInfo;
import xyz.ygmx.test.user.services.IUserService;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
// @GetMapping("getuser")
// public User getUserInfo(){
// User user = new User();
// user.setUid(1);
// user.setUsername("喵喵喵");
// return user;
// }
// @GetMapping("setuser")
// public User setUserInfo(User user){
//
// return user;
// }
//通过名字查询用户
@GetMapping("getuserbyname/{username}")
public UserInfo getUserByName(@PathVariable String username){
UserInfo ui = userService.getByName(username);
return ui;
}
//这个是通过Mapper创建的用户
@GetMapping("createuserbymapper")
public int createUser_1(UserInfo userInfo){
int res=userService.createUserByMapper(userInfo);
return res;
}
//通过 MybatisPlus 自带的方法创建用户
@GetMapping("createuserbyplus")
public boolean createUser_2(UserInfo userInfo){
boolean res=userService.createUser(userInfo);
return res;
}
//通过 MybatisPlus 自带方法修改用户
@GetMapping("edituserbyplus")
public boolean editUserByPlus(int uid,String newName){
boolean res=userService.editUserByPlus(uid,newName);
return res;
}
//通过 Mapper 修改用户
@GetMapping("edituserbymapper")
public int editUserByMapper(int uid,String newName){
int res=userService.editUserByMapper(uid,newName);
return res;
}
//通过MybatisPlus自带方法删除用户
@GetMapping("deleteuserbyplus")
public boolean editUserByPlus(int uid){
boolean res=userService.deleteUserByPlus(uid);
return res;
}
//通过MybatisPlus自带方法删除用户
@GetMapping("deleteuserbymapper")
public int editUserByMapper(int uid){
int res=userService.deleteUserByMapper(uid);
return res;
}
}4、拓展一下
QueryWrapper 和 UpdateWrapper 方法对照表(常用比较)
| 方法 | 含义 | 示例 | 对应sql |
|---|---|---|---|
| eq | 等于 | eq(UserInfo::getName, "张三"); | `name`='张三' |
| ne | 不等于 | ne(UserInfo::getName, "张三"); | `name`<>'张三' |
| gt | 大于 | gt(UserInfo::getAge, 20); | `age`>20 |
| lt | 小于 | lt(UserInfo::getAge, 20); | `age`<20 |
| ge | 大于等于 | ge(UserInfo::getAge, 20); | `age`>=20 |
| le | 小于等于 | le(UserInfo::getAge, 20); | `age`<=20 |
| between | 在区间内 | between(UserInfo::getAge, 20,30); | `age`>=20 and `age`<=30 |
| like | 模糊匹配(包含“张”的) | like(UserInfo::getName, "张"); | `name` like '%张%' |
| likeRight | 模糊匹配(以“张”开头的) | likeRight(UserInfo::getName, "张"); | `name` like '张%' |
| likeLeft | 模糊匹配(以“三”结尾的) | likeLeft(UserInfo::getName, "三"); | `name` like '%三' |

微信扫码查看本文
发表评论