@DynamicUpdate //自動更新updatetime的問題
@DynamicUpdate //自動更新updatetime
在數(shù)據(jù)庫中的字節(jié),包括updatetime,但是我更新某一個內(nèi)容時,updatetime,沒有自動更新,這時候我們只需要在data類中加上注解 @DynamicUpdate 動態(tài)更新的意思
@Entity @DynamicUpdate //自動更新(動態(tài)更新)updatetime public class ProductCategory { /*類目Id*/ @Id //主鍵 @GeneratedValue(strategy = GenerationType.IDENTITY) //子增類型 private Integer categoryId; /*類目名字*/ private String categoryName; /*類目編號*/ private Integer categoryType; /*創(chuàng)建時間*/ 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 注解使用及注意事項
使用場景
平時在寫業(yè)務(wù)時, 會涉及到某條數(shù)據(jù)的更新。 當(dāng)我們使用hibernate的 this.getCurrentSession().saveOrUpdate(o) 更新對象時,會默認的更新對象(o)所有的字段,包括屬性為null和未修改的字段也會更新到原有的數(shù)據(jù)庫表中。
造成了原有的數(shù)據(jù)丟失或數(shù)據(jù)重復(fù)修改。
通常這情況下我們所希望的是僅更新對象(o)中修改過且有值的字段,此時就需要用到@DynamicUpdate注解。
注解使用
標注位置: 實體映射類上
注意事項
根據(jù)官方接口文檔所說,如果我們在使用該注解時必須同時使用 @SelectBeforeUpdate 注解表明在更新前先進行查詢操作。否則是即使聲明該注解也是無效的。
個人理解:
也就是說當(dāng)我們要更新的對象不在session會話的管理中,無法比對哪個字段需要更新,則所標注的注解無效。故需要在其更新前進行查詢,此時當(dāng)前數(shù)據(jù)已經(jīng)在sessio的會話中,即可動態(tài)更新數(shù)據(jù)。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

Java web基礎(chǔ)學(xué)習(xí)之開發(fā)環(huán)境篇(詳解)

eclipse實現(xiàn)ElGamal數(shù)字簽名

教你用java?stream對集合中的對象按指定字段進行分組并統(tǒng)計

Java中使用synchronized關(guān)鍵字實現(xiàn)簡單同步操作示例

redis分布式鎖RedissonLock的實現(xiàn)細節(jié)解析

關(guān)于MyBatis 查詢數(shù)據(jù)時屬性中多對一的問題(多條數(shù)據(jù)對應(yīng)一條數(shù)據(jù))