本文是根据(慕课网)老猿的视频并参考其他资料写的,感兴趣的各位可以到这个视频地址观看:https://www.imooc.com/learn/1130
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变(Comment),为简化开发、提高效率而生。
官方地址
愿景
成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
MyBatis优劣势之分
优势 | 劣势 |
---|---|
SQL语句可以自由控制,更灵活,性能较高(相比较JPA而言) | 简单CRUD操作还需要写SQL语句 |
SQL与代码分离,易于阅读与维护 | XML中有大量的SQL语句要维护 |
提供XML标签,支持编写动态SQL语句 | MyBatis自身功能很有限,但支持Plugin |
lombok简介
Lombok 会在编译时加入 GET/SET 、hashcode 等方法,其生成的方法会根据当前被标记的 javabean 属性的注解等动态生成,避免手动生成 GET/SET 方法时,当属性需求发生变化删改时,频繁的修改 javabean 中的GET/SET 、EQUALS 等带来不必要的工作量
步骤
id | name | age | manager_id | create_time | |
---|---|---|---|---|---|
1087982257332887553 | 大boss | 40 | [email protected] | 2019-01-11 14:20:20 | |
1088248166370832385 | 王天风 | 25 | [email protected] | 1087982257332887553 | 2019-02-05 11:12:22 |
1088250446457389058 | 李艺伟 | 28 | [email protected] | 1088248166370832385 | 2019-02-14 08:31:16 |
1094590409767661570 | 张雨琪 | 31 | [email protected] | 1088248166370832385 | 2019-01-14 09:15:15 |
1094592041087729666 | 刘红雨 | 32 | [email protected] | 1088248166370832385 | 2019-01-14 09:48:16 |
spring:
datasource:
driver-class-name:com.mysql.cj.jdbc.Driver
url:jdbc:mysql://localhost:3306/mp?useSSL=false&serverTimezone=GMT%2B8
username:root
注解 | 作用 |
---|---|
@SpringBootApplication | 标识该类为SpringBoot的启动类 |
@Data | lombok,用于简化代码,自动添加get,set方法 |
@MapperScan("") | mapper扫描器,引号内写mapper包路径 |
@Autowired | 注入依赖,如mapper |
@SpringBooTest | 标识该类可以运行基于SpringBoot的测试 |
@Runwith(SpringRunner.class) | 代表其可以在SpringBoot环境下运行对应类的测试 |
//插入一条记录,@param entity 实体对象
int insert(T entity);
注解 | 作用 |
---|---|
@TableName(“表名”) | 当表名与实体类名不一致时,可以在实体类上加入@TableName()声明 |
@TableId | 声明属性为表中的主键(若属性名称不为默认id) |
@TableFieId(“字段”) | 当实体类属性与表字段不一致时,可以用来声明 |
代码 | 含义 |
---|---|
logging: | 日志 |
level: | 日志级别 |
root:warn | 分日志的warn级别 |
com.mp.dao:trace | 输出该包的trace级别日志(trace级别为日志的最低级别) |
pattern:console: | 日志的输出格式 |
‘%p%m%n’ | 日志级别、日志内容、换行 |
// 根据 ID 查询,@param id 主键ID
T selectById(Serializable id);
// 查询(根据ID 批量查询),@param idList 主键ID列表(不能为 null 以及 empty)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件),@param columnMap 表字段 map 对象
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
测试例子
注:Map中的K值储存的是数据库中的列,并不是实体中的属性名
// 根据 entity 条件,查询全部记录,@param queryWrapper 实体对象封装操作类(可以为null)
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
测试例子
注:条件构造器中具体的各个方法使用介绍可以到该网址查看:https://mp.baomidou.com/guide/wrapper.html#abstractwrapper
Condition的源码可知其继承自Wrapper方法,所以Wrapper的方法都可以使用
where 查询 根据entity new user 设定关键字段查询,也可以理解为 前端传入的搜索参数 但是没有like操作
allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
个别参数说明:
params : key为数据库字段名,value为字段值
null2IsNull : 为true则在map的value为null时调用
isNull 方法,为false时则忽略value为null的
// 根据 Wrapper 条件,查询全部记录,@param queryWrapper 实体对象封装操作类(可以为null)
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
注:Map 中的 String 数据库中的列,Object对应的是列的值,以map的形式,比实体类的优势在于选择查询时,不会有那么多null的字段键返回.
// 根据 Wrapper 条件,查询总记录数,@param querWrapper 实体对象封装操作类(可以为null)
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 entity 条件,查询一条记录,@param queryWrapper 实体对象封装操作类(可以为null)
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
作用:防止编码时误写!
在Mapper文件中定义一个方法
@Select("select * from user ${ew.customSqlSegment}")
List<User> selectAll(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
将sql写入xml中
在application中加入扫描mapper文件路径
mybatis-plus:
mapper-locations: com/mp/mapper/*
在*Mapper.xml中写sql
<mapper namespace="com.mp.dao.UserMapper">
<select id="selectAll" resultType="com.mp.entity.User">
select * from user ${ew.customSqlSegment}
select>
mapper>
分页在网站使用的十分多
配置拦截器组件
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
// 根据 whereEntity 条件,更新记录
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);
参数说明
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 (set 条件值,可为 null) |
Wrapper | updateWrapper | 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) |
// 根据 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);
参数说明
类型 | 参数名 | 描述 |
---|---|---|
Wrapper | wrapper | 实体对象封装操作类(可以为 null) |
Collection extends Serializable> | idList | 主键ID列表(不能为 null 以及 empty) |
Serializable | id | 主键ID |
Map |
columnMap | 表字段 map 对象 |
通过实体类对象直接实现CRUD
实体类操作:
@Data
@EqualsAndHashCode(callSuper = false)
public class User extends Model<User> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "用户id")
private String userId;
}
dao层Mapper接口操作:
public interface UserMapper extends BaseMapper<RentDetail> {
}
测试例子
配置:
public interface UserService extends IService<User>{
}
public class UserServiceImpl extend ServiceImol<UserMapper,User> implements UserService{
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest{
@Autowired
private UserService userService;
//取一个值
@Test
public void getOne(){
User one = userService.getOne(Wrapper.<User>lambdaQuery().gt(User::getAge,25),false);
}
//批量插入
@Test
public void batch(){
User user1= new User();
user1.steName("fan");
user1.setAge("22");
User user2= new User();
user1.steName("fanfan");
user1.setAge("18");
List<User> userList =Arrays.asList(user1,user2);
userService.saveBatch(userList);
}
//查询
@Test
public void chain(){
userService.lambdaQuery().ge(User::getAge,25).like(User::getName,"雨").list();
}
}
作者BB:难顶,原本以为4小时的视频内容应该不多,结果现实给了一巴掌。现在只能总结出这些,后续找时间再重新温习更新。