在线教育日志记录
第一天:基础配置(yml 包括连接数据库,以及打印sql输出日志)
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/education?serverTimezone=UTC
username: root
password: root
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
1.1:利用mp实现自动填充
第一步:先创建数据库两个字段,以及实体类
@TableId(type = IdType.AUTO)
private Long id;
@TableField(fill = FieldFill.INSERT,value = "create_time")
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE,value = "update_time")
private Date updateTime;
第二步:创建一个类,实现接口MetaObjectHandler,实现接口里面的方法
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//使用mp实现一个添加操作,这个方法会执行
@Override
public void insertFill(MetaObject metaObject) {
//设置属性值,通过名字,第二个参数就是属性值,因为在这里只用获取时间,所以new一个date即可
//第三个参数和方法中的参数一样,叫元数据,就比如说一张表里面的表名,字段,都是元数据
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//使用mp实现一个修改操作,这个方法会执行
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
以上如果没问题是可以实现正常自动填充时间的,如果要实现插入的时候自增id,除了在数据库中设置id自增以外,在实体类中,同样要加上注解,利用的是mp的策略,同时也有一个小问题需要注意,可能会引起自动注入失败,就是目录一定要放好,启动类和平常写的bean包,controller包等等要在一个统一的包下面,否则就可能导致自动注入失败。
1.2 mp实现分页查询
简单的利用test写一下,第一步是配置类,这个一定要去写,第二步就是分页操作
@Test
public void testpage(){
//new一个page对象
Page<User> page = new Page<>(1,3);
//把查询到的数据封装到page里面
userMapper.selectPage(page,null);
//这样就可以查询里面的数据
System.out.println(page.getRecords());//获取用户信息
System.out.println(page.getCurrent());//获取当前页
System.out.println(page.getTotal());//获取全部页数
}
配置类
@Configuration
public class MpConfig {
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
条件查询:利用QueryWrapper
@Test
public void testwrapper(){
//创建一个QueryWrapper对象
QueryWrapper<User> wrapper = new QueryWrapper<>();
//ge gt le lt分别是大于,大于等于,小于,小于等于
wrapper.ge("id",3);//column表示的是字段名称,后面就是值
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
//eq ne分别是等于,不等于,符号是<>
wrapper.eq("name","Tom");
List<User> users1 = userMapper.selectList(wrapper);
System.out.println(users1);
//like可以做模糊查询
wrapper.like("name","T");
List<User> users2 = userMapper.selectList(wrapper);
System.out.println(users2);
//orderByDesc排序
wrapper.orderByDesc("age");
List<User> users3 = userMapper.selectList(wrapper);
System.out.println(users3);
//指定要查询的列
wrapper.select("name","age");
List<User> users4 = userMapper.selectList(wrapper);
System.out.println(users4);
}