大家好,我是程序员walker
一个持续学习,分享干货的博主
关注公众号【I am Walker】,一块进步
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
在applicatoin.yml中配置参数
spring:
# 数据库配置
datasource:
url: jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimeZone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatisplus配置
mybatis-plus:
# 配置xml路径
mapper-locations: classpath*:/mapper/**/*.xml
配置@MapperScan
,这一步的目的,主要是扫描到Mapper类
package com.walker.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//配置mapperscan 扫描mapper下的类
@MapperScan("com.walker.mybatisplus.mapper")
public class SpringbootMybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisplusApplication.class, args);
}
}
代码主要有以下几类
下面便以表user
为案例,编写对应的类
数据表结构
CREATE TABLE `user` (
`id` varchar(64) NOT NULL,
`username` varchar(64) DEFAULT NULL,
`password` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
package com.walker.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
//@Data是lombok的注解,用于自动生成setter和getter方法
@Data
@TableName("user") //对应数据库的表名
//Serializable:代表这个类可进行序列化
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String username;
private String password;
private String name;
}
package com.walker.mybatisplus.mapper;
import com.walker.mybatisplus.entity.UserEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
//继承BaseMapper类,这个类是mybatisplus自己封装的,内部
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}
package com.walker.mybatisplus.service;
import com.walker.mybatisplus.entity.UserEntity;
import com.baomidou.mybatisplus.extension.service.IService;
//接口类,继承IService
public interface UserService extends IService<UserEntity> {
}
Iservice方法是mybatisplus自己整合的方法,其中有很多已经整理好的增删改查方法,不需要自己再去重新写,这也是使用mybatisplus的方便之处
@Service(value = "userService") //这里需要添加@Service注入容器
//继承ServiceImpl 其中的泛型注意一定要填写
//实现Iservice
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity>
implements UserService {
}
package com.walker.mybatisplus.controller;
//@RestController:Json字符串的形式返回给客户端,如果不需要强制定义的话,就使用@Controller
@RestController
//请求映射,定义url
@RequestMapping("/user")
public class UserController {
}
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.walker.mybatisplus.mapper.UserMapper">
mapper>
当然,每次这样子自己编写肯定是很麻烦的了,特别是表比较多的时候,所以还是要使用mybatisplus中的代码生成器了
官方文档:https://baomidou.com/pages/779a6e/#%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8
当然也可以参照我以前的文章
【springboot系列】使用mybatisplus代码生成器
本次代码实践都在springboot的test中进行,方便快速地进行调用,基础代码如下,后面实践的代码可以自己进行补充
@SpringBootTest
public class WalkerMybatisPlusTest {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
}
/**
* 查找单个
*/
@Test
public void testGetOne(){
//方式一;使用QueryWrapper 但是对于列名需要自己手动写,所以相对而言还是Lambda比较方便
QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
userEntityQueryWrapper.eq("username","walker");
UserEntity one = userService.getOne(userEntityQueryWrapper);
System.out.println(one);
//方式二:使用lambda表达式
UserEntity walker = userService.getOne(new LambdaQueryWrapper<UserEntity>()
.eq(UserEntity::getUsername, "walker"));
System.out.println(walker);
}
可能出现异常
1、One record is expected, but the query result is multiple records
原因:getOne查询的是单个的,如果查到数据库有多条,则会抛出异常
/**
* 查询多个
*/
@Test
public void testList(){
QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
wrapper.eq("name","xiaoming");
List<UserEntity> list = userService.list(wrapper);
System.out.println(list);
List<UserEntity> userEntities = userService.list(new LambdaQueryWrapper<UserEntity>()
.eq(UserEntity::getName, "xiaoming"));
System.out.println(userEntities);
}
1、添加插件配置
package com.walker.mybatisplus.common.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,
* 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
* 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2、测试代码
/**
* 分页
*/
@Test
public void testPage(){
/**
* 方式一:使用wrapper和page进行分页查询
*/
Page<UserEntity> page = new Page<>();
page.setCurrent(1);
page.setSize(1);
QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
wrapper.eq("name","xiaoming");
Page<UserEntity> userEntityPage = userService.page(page, wrapper);
System.out.println(userEntityPage);
/**
* 方式二:使用mapper.xml进行编写
*/
Page<UserEntity> mapperPage = userMapper.pageByName(page, "xiaoming");
System.out.println(mapperPage);
}
方式二的其他代码:
Mapper类
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
Page<UserEntity> pageByName(Page<UserEntity> page, @Param(value = "name") String name);
}
xml文件
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.walker.mybatisplus.mapper.UserMapper">
<select id="pageByName" resultType="com.walker.mybatisplus.entity.UserEntity">
select * from user
where name=#{name}
select>
mapper>
返回结果:
records:记录,我们查到的数据就在这里
total:总数,就是数据库中查到的数据的总数
size:每页的长度,这个是我们自己定义的
current:当前的页数
两者都有各自的优缺点,但在实际应用中,方式二应该是比较多的,主要是他比较容易维护,查询sql存放于xml中,但是就需要一定的sql能力
而使用wrapper对于简单的sql的话,是一定帮助的,但是对于较复杂的分页查询,那么是不大推荐的
@Test
public void testSave(){
//新增单个
UserEntity userEntity = new UserEntity();
userEntity.setUsername("BB");
userEntity.setPassword("aa");
userEntity.setName("xxx");
userService.save(userEntity);
//批量新增
ArrayList<UserEntity> userEntities = new ArrayList<>();
UserEntity tempUser;
for (int i = 0; i < 5; i++) {
tempUser=new UserEntity();
tempUser.setName("a"+i);
tempUser.setUsername("b"+i);
tempUser.setPassword("123");
userEntities.add(tempUser);
}
userService.saveBatch(userEntities);
}
@Test
public void update(){
//单个修改
//使用wrapper
UpdateWrapper<UserEntity> wrapper = new UpdateWrapper<>();
wrapper.eq("username","walker");
wrapper.set("password","1111111111");
boolean update = userService.update(wrapper);
System.out.println(update);
//使用lambda wrapper
boolean update1 = userService.update(new LambdaUpdateWrapper<UserEntity>()
.eq(UserEntity::getUsername, "walker")
.set(UserEntity::getPassword, "aa"));
System.out.println(update1);
//根据id进行修改
//这个方法会对值不为null的列进行修改
UserEntity walker = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, "walker"));
walker.setPassword("bbbbbbbbbbbbbbbb");
userService.updateById(walker);
}
@Test
public void testSaveOrUpdate(){
/**
* 新增或者修改
* 这个方法的原理是:首先根据id去查询库中是否有数据,如果有的话,则进行修改
* 如果没有的话,则进行新增
*/
UserEntity userEntity = new UserEntity();
userEntity.setId("1111");
userEntity.setUsername("wwww");
userEntity.setPassword("bbbbbbbbbb");
userService.saveOrUpdate(userEntity);
/**
* 批量新增或修改,原理差不多,只是多了个数组而已
* 也是先根据id去进行查询
*/
ArrayList<UserEntity> userEntities = new ArrayList<>();
for (int i = 0; i < 5; i++) {
UserEntity userEntity1 = new UserEntity();
userEntity1.setPassword("a");
userEntity1.setUsername("aaaaaaaa"+i);
userEntities.add(userEntity1);
}
userService.saveOrUpdateBatch(userEntities);
}
@Test
public void testDel(){
//根据wrapper移除
QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
wrapper.eq("username","aaaaaaaa0");
userService.remove(wrapper);
//根据lambdawrapper移除
userService.remove(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername,"aaaaaaaa1"));
//根据id移除
userService.removeById("1111");
//根据类的id移除
UserEntity userEntity = new UserEntity();
userEntity.setId("1525765938643283971");
userService.removeById(userEntity);
//根据id数组移除,相当于批量移除
ArrayList<String> ids = new ArrayList<>();
ids.add("1526572897000767490");
ids.add("1526572906890936322");
userService.removeBatchByIds(ids);
//根据map移除
HashMap<String, Object> map = new HashMap<>();
map.put("username","b4");
userService.removeByMap(map);
}