一、CRUD扩展
1、插入操作
//插入测试
@Test
public void testInsert(){
User user = new User();
//id值会帮我们自动生成
user.setName("hcz2");
user.setAge(22);
user.setEmail("2003424234@qq.com");
int result = userMapper.insert(user);
System.out.println("受影响行数"+result);
System.out.println(user);
}
注意:数据库插入的id默认为全局的唯一id
2、主键生成策略
(1)分布式系统唯一id生成:雪花算法
- 雪花算法(SnowFlake) 是twitter公司内部分布式项目采用的ID生成算法,开结果是一个Long型的id。其核心思想是:使用41bit作为毫秒数,10bit作为机器的id(5bit是数据中心,5bit是机器id),12bit作为毫秒内的流水号(意味着每一个节点在毫秒内可以产生4096个id),最后还有一个符号位,永远是0。
(2)主键自增:
1、默认是:ID_WORKER_STR
public enum IdType {
AUTO(0),//数据库id自增
NONE(1),//未设置主键
INPUT(2),//手动输入
ID_WORKER(3),//默认的全局唯一id
UUID(4),//全局唯一id
ID_WORKER_STR(5);//字符串表示法
}
2、需要配置主键自增
- A、在实体类上添加注解
@TableId(type = IdType.AUTO)
- B、数据库id字段一定要是自增的,否则会报错
- C、再次测试插入一条没有给定id的数据
3、更新操作
//测试更新
@Test
public void testUpdate(){
User user = new User();
user.setId(1381507854178152449L);
user.setName("zs");
//注意:updateById参数是一个对象
int i = userMapper.updateById(user);
System.out.println(i);
}
当在上面的基础之上在添加一个修改年龄,发现其可以动态拼接SQL语句
4、自动填充
- 创建时间,修改时间,这些操作都是自动完成的,我们不希望手动更新
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上,而且需要自动化
方式一:数据库级别(不建议使用)
1、在表中新增字段create_time,update_time
2、测试插入更新操作,需要重新更新实体类属性
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
/**
* id对应数据库中的主键(uuid,自增id,雪花算法,redis)
*/
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private int age;
private String email;
private Date createTime;
private Date updateTime;
}
方式二:代码级别
1、让数据库恢复默认状态和进行更新操作
2、实体类的字段属性上需要增加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3、编写时间处理器类来处理这个注解即可
@Slf4j
@Component //记得将该处理器添加到IOC容器中去
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("开始插入操作");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//更新时填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("开始更新操作");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
注意:
- 字段必须声明TableField注解,属性 fill 选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段
- 填充处理器MyMetaObjectHandler在 Spring Boot 中需要声明@Component或@Bean注入
4、测试插入更新操作观察时间
5、查询操作
(1)查询单条数据
//测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
(2)查询多条数据
//查询多条记录
@Test
public void testSelectByBatchId(){
/*List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);*/
List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
users.forEach(user-> System.out.println(user));
}
(3)条件查询
//条件查询 -- 使用map集合
@Test
public void testSelectByMap(){
//自定义要查询的条件
Map<String,Object> map = new HashMap<>();
map.put("name","hcz2");
List<User> users = userMapper.selectByMap(map);
users.forEach(user-> System.out.println(user));
}
(4)分页查询
A、配置拦截器组件即可
@MapperScan("com.hcz.mapper")
@EnableTransactionManagement
@Configuration //配置类
public class MybatisPlusConfig {
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
B、测试
//测试分页查询
@Test
public void testPage(){
//参数1:当前页 参数2:页面大小
Page<User> pages = new Page<>(2,5);
userMapper.selectPage(pages,null);
pages.getRecords().forEach(page-> System.out.println(page));
}
6、删除操作
(1)基本删除(包括删除一条数据、多条数据、条件删除)
//测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1381507854178152453L);
}
//删除多条记录
@Test
public void testDeleteBatchIds(){
userMapper.deleteBatchIds(Arrays.asList(1381507854178152452L,1381507854178152450L));
}
//条件删除 -- 使用map集合
@Test
public void testDeleteMap(){
Map<String,Object> map = new HashMap<>();
map.put("name","hcz2");
userMapper.deleteByMap(map);
}
(2)逻辑删除
- 物理删除:从数据库中直接移除
- 逻辑删除:在数据库中没有被移除,而是通过一个变量来让它失效。deleted=0 => deleted=1
1、在数据表中添加一个deleted字段
2、实体类中增加属性并添加一个注解
/**
* 逻辑删除
*/
@TableLogic
private Integer deleted;
3、配置逻辑删除组件
@MapperScan("com.hcz.mapper")
@EnableTransactionManagement
@Configuration //配置类
public class MybatisPlusConfig {
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
//逻辑删除组件
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
}
4、在SpringBoot配置文件中配置逻辑删除
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1 # 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-not-delete-value=0 # 逻辑未删除值(默认为 0)
5、测试删除操作