官方文档地址:
https://mp.baomidou.com/guide/#%E7%89%B9%E6%80%A7
使用第三方组件:
1.导入依赖
2.研究依赖如何配置
3.代码编写及其提升
1.创建数据库,和表信息
2.创建springboot项目,初始化项目
3.导入依赖(不要同时导入mybatis和mybatis-plus)
5.连接数据库
spring.datasource.password=123456 spring.datasource.username=root spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
(传统方式)6.pojo-dao(连接mybtis并且配置mapper.xml文件)-service-controller
(使用mybatis-plus)6.pojo - mapper(只需要mapper接口继承baseMapper就能实现)- service-controller
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
//使用了MybatisPlus之后只要在对应的mapper上继承baseMapper
@Repository
public interface UserMapper extends baseMapper {
//所有的CRUD操作已经完成了
}
@MapperScan("com.cs.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
@SpringBootTest
class MybatisPlusApplicationTests {
//此时mapper已经继承了baseMapper中的方法(基本的CRUD),当然我们也能编写我们自己的方法
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
List userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
}
注意:需要用在主启动类中扫描mapper下的接口
用@MapperScan(“com.cs.mapper”)
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
CRUD扩展 主键的生成策略之一—雪花算法雪花栓法是推特的分布式ID生成算法,结果会生成一个long型的Id,能达到毫秒内的id分布,几乎是全球唯一.
实现主键自增
1.在实体类字段上增加注解@TableId(type = IdType.AUTO)
关于IdType的其余解释:
public enum IdType {
AUTO(0),//数据库id自增
NONE(1),//设置主键
INPUT(2),//手动输入,一旦用这个需要手动添加Id
ID_WORKER(3),//默认全局Id
UUID(4),//全局唯一Id
ID_WORKER_STR(5);//ID_WORKER的字符串
private int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
2.数据库字段一定要改为自增
插入操作 @Test
public void testInsert(){
User user = new User();
user.setAge(3);
user.setEmail("aaaaa@.ccc");
user.setName("sxc");
int result = userMapper.insert(user);//自动生成的ID1442420902178054146
System.out.println(result);
System.out.println(user);
}
更新操作
@Test
public void testUpdate(){
User user = new User();
user.setId(5L);
user.setName("testUpdate");
//虽然是ById但是参数是个泛型
int i = userMapper.updateById(user);
}
//=================
@Test
public void testUpdate(){
User user = new User();
user.setId(5L);
user.setName("testUpdate");
user.setAge(12);
//相比前面的更新,我们多添加了age这一项,但是 MyBatisPlus已经帮助我们自动生成了动态sql语句
int i = userMapper.updateById(user);
}
时间的自动填充:
当出现创建时间,修改时间,这些操作最好是自动完成,不要手动更新.
方式一:数据库级别修改
1.在表中新增字段 create_time,update_time
ALTER TABLE mybatis-plus.user ADD COLUMN create_time DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT ‘创建时间’ AFTER email, ADD COLUMN update_time DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT ‘修改时间’ AFTER create_time;
tips:记得把update_time更新那一栏后面勾选更新
2.把实体类同步,再次测试插入方法就自动更新时间了
private Date createTime;
private Date updateTime;
方式二:代码级别修改
1.删除数据库create_time,update_time下面的默认值
2.在实体类的对应的字段属性上增加注解
//字段自动填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
3.编写处理器来处理这个注解
@Component
@Slf4j
public class MymetaObjectHandler implements metaObjectHandler {
//插入时的填充策略
@Override
public void insertFill(metaObject metaObject) {
log.info("start insert =========");
//设置createTime属性,插入的值时一个Date,传入一个metaObject
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//更新时的填充策略
@Override
public void updateFill(metaObject metaObject) {
log.info("start update =========");
//设置createTime属性,插入的值时一个Date,传入一个metaObject
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
4.测试插入和更新
乐观锁
乐观锁:总是认为任务不会出现问题,无论干什么都不上锁,如果出现问题,再次更新值测试(添加版本)
悲观锁:总是认为任务总会出现问题,无论干什么都上锁,再去操作
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion - - where version = oldVersion
- 如果version不对,就更新失败
1.批量查询
@Test
public void testQuery(){
User user1 = userMapper.selectById(6L);
List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
for (User user : users) {
System.out.println(user);
}
System.out.println(user1);
}
2.条件查询
@Test
public void testSelectByBatchIds(){
HashMap hashMap = new HashMap<>();
hashMap.put("name","Tom");
//从表中查询name = Tom的用户
List users = userMapper.selectByMap(hashMap);
for (User user : users) {
System.out.println(user);
}
}
3.分页查询
(1)原始的Limit
(2)pageHelper第三方插件
(3)MyBatisPlus内置的分页插件
第三个实现:
1.配置拦截器即可
//注册分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
2.直接使用page对象
@Test
public void testPage(){
//使用分页操作:第一页,页面大小为5
Page page = new Page<>(1, 5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
//总数
System.out.println(page.getTotal());
}
删除操作
物理删除:数据库中移除
@Test
public void testDeleteById(){
//通过Id进行批量删除
userMapper.deleteBatchIds(Arrays.asList(6,8));
//条件删除
HashMap map = new HashMap<>();
map.put("age",3);
userMapper.deleteByMap(map);
}
逻辑删除:数据库中没有删除,通过一个变量让其失效,类似回收站
步骤:
1.在数据表中增加一个deleted字段
2.在响应的pojo中添加属性
//逻辑删除字段
@TableLogic
private Integer deleted;
3.配置逻辑删除设置
#配置逻辑删除 mybatis-plus.global-config.db-config.field=flag mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0性能分析插件
作用:分析每条sql执行操作的时间
所以当我们遇见慢sql时,超过一定时间我们可以限制停止运行.
使用步骤:
1.导入插件
@Bean
@Profile({"dev","test"})//只在dev,test环境中运行
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);//设置sql最大时间时1ms,超过后不执行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
注意:在springboot中环境配置为dev或test环境
# 设置开发环境 spring.profiles.active=dev
2.测试使用sql语句即可
条件构造器(重要)写复杂的sql可以用它来替代实现:
1.多条件查询
@Test
void contextLoads() {
//查询name不为空,年龄大于12岁
//这个wapper可以类比为mapper,用于修改user中的条件
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")//不为空
.ge("age",12);//大于
userMapper.selectList(wrapper).forEach(System.out::println);
}
@Test
void Test(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("name","Tom");//相等
System.out.println(userMapper.selectOne(wrapper));
}
@Test
void Test1(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.between("age",3,21);//在..之间
Integer count = userMapper.selectCount(wrapper);
System.out.println(count);
}
2.模糊查询
@Test
void Test2(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.notLike("name","o")//name中没有"o"
.likeRight("email","t");//email的右开头是t
List
3.嵌套子查询
@Test
void Test3(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id < 4");//其中id是在另一表中获得的
List
4.排序查询
@Test
void Test4(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
List
5.多表查询
//



