测试
//测试更新功能
@Test
public void testUpdate(){
User user = new User();
//通过调节自动拼接动态sql
user.setId(6L);
user.setName(“kkkk”);
user.setAge(9999);
//updateById 其参数是一个对象
int i = userMapper.updateById(user);
System.out.println(i);
}
方式二:代码级别
1、删除数据库的默认值、更新操作!
2、实体类的字段属性上需要增加注解
//记住用util包下的Date!!
//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3、编写处理器来处理这个注解
package com.kk.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component //一定要注意把处理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时候的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info(“start insert fill … …”);
this.setFieldValByName(“createTime”,new Date(),metaObject);
this.setFieldValByName(“updateTime”,new Date(),metaObject);
}
//更新时候的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info(“start insert fill … …”);
this.setFieldValByName(“updateTime”,new Date(),metaObject);
}
}
测试
//测试插入功能
@Test
public void testInsert(){
User user = new User();
// user.setId(6L);
user.setName(“qq”);
user.setAge(17);
user.setEmail(“30666@qq.com”);
//这里需要一个User对象,所以需要new一个User
int result = userMapper.insert(user); //帮我们自动生成id
System.out.println(result);//受影响的函行数
System.out.println(user);//发现,id会自动回填
}
//测试更新功能
@Test
public void testUpdate(){
User user = new User();
//通过调节自动拼接动态sql
user.setId(1442085733983649796L);
user.setName(“kkkk”);
user.setAge(99999);
//updateById 其参数是一个对象
int i = userMapper.updateById(user);
System.out.println(i);
}
5、乐观锁
乐观锁:顾名思义,总是认为不会出现问题,无论干什么不去上锁!如果出现了问题,再次更新值测试
悲观锁:顾名思义,总是认为会出现问题,无论干什么都上锁!再去操作!
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时,set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
l乐观锁:1、先查询,获取版本号 version=1
— A线程
update user set name=“kk”,version=version+1
where id=2 and version=1
— B 线程 抢先完成 ,这个时候 version=2 会导致A修改失败
update user set name=“kk”,version=version+1
where id=2 and version=1
测试MP的乐观锁插件
1、给数据库中增加version字段
2、实体类增加对应的字段
@Version //代表乐观锁的注解
private Integer version;
3、注册组件
package com.kk.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableT