@DynamicUpdate //自动更新updatetime 在数据库中的字节,包括updatetime,但是我更新某一个内容时,updatetime,没有自动更新,这时候我们只需要在data类中加上注解 @DynamicUpdate 动态更新的意思
@DynamicUpdate //自动更新updatetime
在数据库中的字节,包括updatetime,但是我更新某一个内容时,updatetime,没有自动更新,这时候我们只需要在data类中加上注解 @DynamicUpdate 动态更新的意思
@Entity @DynamicUpdate //自动更新(动态更新)updatetime public class ProductCategory { /*类目Id*/ @Id //主键 @GeneratedValue(strategy = GenerationType.IDENTITY) //子增类型 private Integer categoryId; /*类目名字*/ private String categoryName; /*类目编号*/ private Integer categoryType; /*创建时间*/ private Date createTime; /*更新时间*/ private Date updateTime; public Integer getCategoryId(int i) { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Integer getCategoryType() { return categoryType; } public void setCategoryType(Integer categoryType) { this.categoryType = categoryType; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "ProductCategory{" + "categoryId=" + categoryId + ", categoryName='" + categoryName + '\'' + ", categoryType=" + categoryType + '}'; } }
@DynamicUpdate 注解使用及注意事项
使用场景
平时在写业务时, 会涉及到某条数据的更新。 当我们使用hibernate的 this.getCurrentSession().saveOrUpdate(o) 更新对象时,会默认的更新对象(o)所有的字段,包括属性为null和未修改的字段也会更新到原有的数据库表中。
造成了原有的数据丢失或数据重复修改。
通常这情况下我们所希望的是仅更新对象(o)中修改过且有值的字段,此时就需要用到@DynamicUpdate注解。
注解使用
标注位置: 实体映射类上
注意事项
根据官方接口文档所说,如果我们在使用该注解时必须同时使用 @SelectBeforeUpdate 注解表明在更新前先进行查询操作。否则是即使声明该注解也是无效的。
个人理解:
也就是说当我们要更新的对象不在session会话的管理中,无法比对哪个字段需要更新,则所标注的注解无效。故需要在其更新前进行查询,此时当前数据已经在sessio的会话中,即可动态更新数据。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。