【发布时间】:2016-03-02 13:14:44
【问题描述】:
是否可以在不使用休眠修改实体版本的情况下更新数据库中的实体?
使用我的网络应用程序,用户可以创建或更新实体。在任何用户操作之后“处理”这些实体的另一个异步进程在哪里。如果用户在“处理”实体之前打开实体进行更新,但在“处理”后尝试保存它,用户将得到“OptimisticLockException”,并且他输入的所有数据都将丢失。但我想用用户提供的数据覆盖在异步过程中更新的数据。
代码片段来演示为什么我需要这种行为(JPA + Hibernate):
//user creates entity by filling form in web application
Entity entity = new Entity ();
entity.setValue("some value");
entity.setProcessed (false);
em.persist(entity);
em.flush();
em.clear();
//but after short period of time user changes his mind and again opens entity for update
entity = em.find(Entity.class, entity.getId());
em.clear(); //em.clear just for test purposes
//another application asynchronously updates entities
List entities = em.createQuery(
"select e from Entity e where e.processed = false")
.getResultList();
for (Object o: entities){
Entity entityDb = (Entity)o;
someTimeConsumingProcessingOfEntityFields(entityDb); //update lots of diferent entity fields
entityDb.setProcessed(true);
em.persist(entityDb);
}
em.flush(); //version of all processed entities are incremented.
//Is it possible to prevent version increment?
em.clear();
//user modifies entity in web application and again press "save" button
em.merge(entity); //em.merge just for test purposes
entity.setValue("some other value");
entity.setProcessed (false);
em.persist(entityDb);
em.flush(); //OptimisticLockException will occur.
//Is it possible to prevent this exception from happening?
//I would like to overwrite data updated in asynchronous process
//with user provided data.
还有我的实体:
@Entity
@Table(name = "enities")
public class Entity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Version
private int versionNum;
@Column
private String value
@Column
private boolean processed;
//… and so on (lots other properties)
}
实际上我有更多的类有类似的问题 - 所以我正在寻找一些优雅的非侵入性解决方案。
在我看来,这是很常见的情况。但是我找不到任何信息如何实现这样的功能。
【问题讨论】: