MybatisPlus由浅入深
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,旨在简化开发过程。
基本使用步骤
1.依赖引入
<!-- mysql依赖 --> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- MyBatisPlus依赖,向下兼容Mybatis --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency>
2.创建Mapper接口,继承BaseMapper<T>(T表示操作类型)
@Mapper
public interface UserMapper extends BaseMapper<User> {}@Data
public class User {/*@TableId 注解指定name为主键*/@TableIdprivate String name;private Integer age;
}
3.使用
@SpringBootTest
public class MybatisPlusTest {@Autowiredprivate UserMapper userMapper;/*增加*/@Testvoid testInsert() {User user = new User();user.setName("EE");user.setAge(18);userMapper.insert(user);}/*查询*/@Testvoid testSelectById() {User user = userMapper.selectById("Tj");System.out.println("user:" + user);}/*查询一个集合*/@Testvoid testSelectByIds(){List<String> strings = Arrays.asList("Tj", "EE");List<User> users = userMapper.selectBatchIds(strings);users.forEach(System.out::println);}/*删除*/@Testvoid testDeleteById() {userMapper.deleteById("Tj");}/*修改*/@Testvoid testUpdateById() {User user = new User();user.setName("EE");user.setAge(20000);userMapper.updateById(user);}
}
其他注意事项
//注意配置Mysql,连接数据库
spring:datasource:url: jdbc:mysql://localhost:3306/temp?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driver
//MapperScan注解配置扫描文件
@MapperScan("org.example.mapper")
@SpringBootApplication
public class RedisTemplateDemoApplication {public static void main(String[] args) {SpringApplication.run(RedisTemplateDemoApplication.class, args);}}
基本原理
MybatisPlus基于反射
1.将类名驼峰转数据库表下划线;
2.id字段为主键;
3.变量名驼峰转下划线。
若不一样则通过注解指定
@TableName:指定该类映射表名
@TableId:指定成员变量为主键
@TableField:指定成员变量映射的数据库字段
在TableId中可以指定type,@TableId(value = "name", type = IdType.INPUT)
具体如下:
IdType.Auto:Id自增;
IdType.Input:通过set方法传入;
IdType.ASSIGN_ID:通过nextId方法生成Id。
使用TableField场景
成员变量与数据库字段不一致;
成员变量以is开头,且是bool值(在映射时会去掉is前缀,导致不匹配数据库字段);
成员变量名与数据库关键字冲突(比如变量名为select,order等)
成员变量不是数据库字段(@TableField(exist = false)
示例
@Data
@TableName("user")
public class User {/*@TableId 注解指定name为主键*/@TableId(value = "name", type = IdType.INPUT)private String name;@TableField("age")private Integer age;/*非数据库中字段*/@TableField(exist = false)private String email;
}
条件构造器Wrapper
支持创建各种复杂的where条件,满足日常需求。
基本使用
查询
@Testvoid testQueryWrapper(){//若是查询QueryWrapper<User> queryWrapper = new QueryWrapper<>();//设置查询字段queryWrapper.select("name","age")//模糊查询.like("name","E")//where条件:age = 20000.eq("age",20000);List<User> userList = userMapper.selectList(queryWrapper);userList.forEach(System.out::println);}
修改
@Testvoid testQueryWrapper2(){User user = new User();//设置满足条件age = 123user.setAge(123);//设置name = "EE"QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("name","EE");//sql:update user set age = 23 where name = "EE"int update = userMapper.update(user, queryWrapper);System.out.println("update:"+update);}/*根据字段值自增或自减*/@Testvoid testUpdateWrapper(){List<String> names = List.of("EE","aa");//sql: update user set age = age - 100 where name in ("EE","aa")UpdateWrapper<User> updateWrapper = new UpdateWrapper<User>().setSql("age = age -100").in("name",names);int update = userMapper.update(null, updateWrapper);//返回修改的行数System.out.println("update:"+update);}
Lambda表达式
通过::引用方法,避免硬编码
@Testvoid testQueryWrapper(){QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.select("name","age").like("name","E").eq("age",20000);List<User> userList = userMapper.selectList(queryWrapper);userList.forEach(System.out::println);}@Testvoid testLambdaQueryWrapper(){LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>().select(User::getName,User::getAge).like(User::getName,"E").eq(User::getAge,20000);//查询List<User> userList = userMapper.selectList(queryWrapper);userList.forEach(System.out::println);}
自定义SQL
我们可以利用MybatisPlusgou的Wrapper构建复杂Where条件,自定义SQL剩余部分。
1.基于Wrapper构建where条件。
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();queryWrapper.eq(User::getName, "xiaoming");Integer amount = 100;userMapper.updateAgeById(queryWrapper, amount);
2.在mapper方法参数中用Param注解声明Wrapper变量,必须为ew。
3.自定义sql,使用Wrapper条件。
@Update("update user set age = age + #{amount} ${ew.customSqlSegment}")void updateAgeById(@Param("ew") LambdaQueryWrapper<User> queryWrapper,@Param("amount") Integer amount);
ew.customSqlSegment相当于queryWrapper.getCustomSqlSegment()方法,获取自定义sql片段。
MybatisPlus的IService接口
它封装了常见的数据库操作(CRUD),让你无需编写重复的 Service 实现代码。
流程
1.自定义Service接口继承IService接口。
public interface IUserService extends IService<User> {
}
2.自定义ServiceImpl实现类,实现自定义接口并继承ServiceImpl类,ServiceImpl类实现了IService接口中所有方法,不需要我们自己实现。
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {}
3.使用
@Autowiredprivate IUserService userService;@Testvoid testSaveUser() {User user = new User();user.setName("XII");user.setAge(30);boolean checkSave = userService.save(user);System.out.println("checkSave:" + checkSave);}
使用Lambda进行复杂查询
//controller@ApiOperation("查询多用户接口")@GetMapping("/list")List<User> queryUsers(User user) {return userService.queryUsers(user.getName(),user.getAge());}//service@Overridepublic List<User> queryUsers(String name, Integer age) {//查询前先判断是否为nullreturn lambdaQuery().eq(name != null, User::getName, name).ge(age != null, User::getAge, age).list();}
IService批量新增
1.每次插入一个集合,集合中存放千条数据。避免每次插入一条导致频繁的网络请求耗时。
2.在yml配置文件中rewriteBatchedStatements=true,JDBC 驱动会将批量 SQL 重写为 单个多值插入语句,大幅减少与数据库的交互次数,提升性能。