JPA查詢資料後,修改其中的某個值,導致資料庫的值也修改了(JPA的生命週期)
阿新 • • 發佈:2018-11-04
問題描述
在一個迴圈中,通過JPA進行查詢後,修改查詢後的值,導致資料庫的值修改了
for (Integer integer : condition.getResourceIds()) {
List<Integer> tempResourceIds = workTeamDao.findAllTeamListByTeamName(String.valueOf(integer));
SchedulingEvent tempSchedulingEvent =
dao.findTopByStartBetweenAndResourceIdIn(condition.getStart(),
condition.getEnd(),
tempResourceIds);
if (tempSchedulingEvent!=null){
tempSchedulingEvent.setResourceId(integer);
schedulingEvents.add(tempSchedulingEvent);
}
}
問題解決
通過BeanUtils.copyProperties()
方法將查詢的值,賦給新的物件
for (Integer integer : condition.getResourceIds()) {
List<Integer> tempResourceIds = workTeamDao.findAllTeamListByTeamName(String.valueOf(integer));
SchedulingEvent tempSchedulingEvent =
dao.findTopByStartBetweenAndResourceIdIn(condition.getStart(),
condition.getEnd(),
tempResourceIds);
if (tempSchedulingEvent!=null){
SchedulingEvent schedulingEvent = new SchedulingEvent();
BeanUtils.copyProperties(tempSchedulingEvent, schedulingEvent);
schedulingEvent.setResourceId(integer);
schedulingEvents.add(schedulingEvent);
}
}
問題產生原因
JPA有如上所示的四個生命週期:
- New:瞬時物件,尚未有id,還未和Persistence Context建立關聯的物件。
- Managed:持久化受管物件,有id值,已經和Persistence Context建立了關聯的物件。
- Datached:遊離態離線物件,有id值,但沒有和Persistence Context建立關聯的物件。
- Removed:刪除的物件,有id值,尚且和Persistence Context有關聯,但是已經準備好從資料庫中刪除
此處更新
ResourceId
值時,tempSchedulingEvent
已與session
關聯,並且資料庫有資料,已經持久化了,並且在資料庫的快取當中了,當我們對tempSchedulingEvent
使用set()
方法時,快取快取Session
中的資料發生改變,那麼接著資料庫也會跟著進行相應的改變。所以就執行了update
的更新操作。