使用Ebean和Play Framework 2的OptimisticLockException

Ale*_*var 7 ebean playframework-2.0

我在Play Framework 2中使用Ebean,有时会出现类似的OptimisticLockException:

play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[OptimisticLockException: Data has changed. updated [0] rows sql[update manager set modification_time=?, session_id=?, expiration_date=? where id=? and rating=? and creation_time=? and modification_time=? and name=? and surname=? and login=? and password_hash=? and email=? and session_id=? and expiration_date=?] bind[null]]]
Run Code Online (Sandbox Code Playgroud)

当少数演员开始访问数据库时会发生这种情况

那么,Manager类是:

public class Manager extends Model {
@Getter @Setter
Long id;

@Getter @Setter
private String name;

@Getter @Setter
private String surname;

@Column(unique = true)
@Getter @Setter
private String login;

@Getter @Setter
private String passwordHash;

@Getter @Setter
private String email;

@Embedded
@Getter @Setter
private ManagerSession session;

@Getter
private Timestamp creationTime;

@Getter
private Timestamp modificationTime;

@Override
public void save() {
    this.creationTime       = new Timestamp(System.currentTimeMillis());
    this.modificationTime   = new Timestamp(System.currentTimeMillis());
    super.save();
}

@Override
public void update() {
    this.modificationTime   = new Timestamp(System.currentTimeMillis());
    super.update();
}

}
Run Code Online (Sandbox Code Playgroud)

使用save()和update()钩子代替@PrePersist注释,因为Ebean不支持它.据我所知@Version注释总是带来乐观锁定模式,所以我开始使用这样的技巧.我知道Optimistick锁是什么,但是当许多演员应该修改相同的db记录时,这种情况应该如何解决?

小智 15

解:

问题:直接从Play窗体保存分离的EBean模型会导致OptimisticLockException,或者在使用@Version时会导致NullpointerException.

Form<Venue> form = form(Venue.class).bindFromRequest();
form.get().update(id); // this causes the exception
Run Code Online (Sandbox Code Playgroud)

解决方案:在从请求参数绑定之前,表单应支持从数据库向其提供对象.然后,请求中找到的参数将覆盖对象上的相关属性.也许在bindFromRequest()之前调用fill():

Form<Venue> form = form(Venue.class).fill(Venue.find.byId(id)).bindFromRequest();
form.get().update(id);
Run Code Online (Sandbox Code Playgroud)