我们在实际开发过程中,有些字段想使用系统默认值,比如操作的用户信息、数据生成时间等,比较人容的方式我们可以直接写sql时进行强制,但是这样的方式比较麻烦且鸡肋,所以myabatis-plus提供了这样的功能,主要是通过以下方式实现
1.在类成员中增加@TableField((fill = FieldFill.INSERT_UPDATE)
这里的fill值可以填充如下内容,见名就可以思意
public enum FieldFill {
DEFAULT,
INSERT,
UPDATE,
INSERT_UPDATE;
private FieldFill() {
}
}
2.通过实现接口MetaObjectHandler的以下方法来实现
public void insertFill(MetaObject metaObject)
public void updateFill(MetaObject metaObject)
3.可以利用类MetaObject以下方法来进行自动填充的条件判断
public String[] getGetterNames()
public String[] getSetterNames()
public Class<?> getSetterType(String name)
public Class<?> getGetterType(String name)
public boolean hasSetter(String name)
public boolean hasGetter(String name)
public Object getValue(String name)
根据以上介结我们可以搞一个进行测试
1.准备USER类
@Data
public class User extends Model<User> {
private Long id;
private String name;
private Integer age;
private String email;
private int deleted;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime createtime;
}
2.准备实现MetaObjectHandler的类,并标注为@Component
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
System.out.println("insertFill");
setFieldValByName("createtime", LocalDateTime.now(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
System.out.println("updateFill");
setFieldValByName("createtime", LocalDateTime.now(),metaObject);
}
}
3.准备Insert测试方法
@Test
public void testSave(){
for(long i=12;i<13;i++) {
User user = new User();
user.setId(400+i);
user.setAge((int)i+30);
user.setEmail("zoulinlin"+i+"@163.com");
user.setName("zouli"+i);
int row = userMapper.insert(user);
System.out.println(row);
}
}
运行log:
insertFill
2022-10-10 14:23:58.740 DEBUG 2588 --- [ main] c.m.service.mapper.UserMapper.insert : ==> Preparing: INSERT INTO user ( id, name, age, email, deleted, createtime ) VALUES ( ?, ?, ?, ?, ?, ? )
2022-10-10 14:23:58.767 DEBUG 2588 --- [ main] c.m.service.mapper.UserMapper.insert : ==> Parameters: 412(Long), zouli12(String), 42(Integer), zoulinlin12@163.com(String), 0(Integer), 2022-10-10T14:23:56.361(LocalDateTime)
2022-10-10 14:23:58.915 DEBUG 2588 --- [ main] c.m.service.mapper.UserMapper.insert : <== Updates: 1
1
4.准备UPDATE测试方法
@Test
public void testUpate(){
UpdateWrapper<User> updateWrapper=new UpdateWrapper<User>();
updateWrapper.eq("id",2) ;
User user=new User();
user.setName("zzzz");
user.setAge(100);
userMapper.update(user,updateWrapper);
}
运行log:
@Test
public void testUpate(){
UpdateWrapper<User> updateWrapper=new UpdateWrapper<User>();
updateWrapper.eq("id",2) ;
User user=new User();
user.setName("zzzz");
user.setAge(100);
userMapper.update(user,updateWrapper);
}