我正在使用带有休眠实现的 JPA2.0 的 Play2.1.1 Java。
通过代码而不是像下面那样使用@transactional 来控制事务是正常的JPA 代码样式,有没有办法像下面一样在Play 中工作?或者如何使用 JPA.withtranaction() 来做?我试过了,不知道如何传入参数,我对功能代码不熟悉。多谢。请根据以下内容给我一些示例代码。
public void createActorB(final String email, final String psw) throws Throwable {
EntityManager manager = JPA.em();
try {
EntityTransaction ex = manager.getTransaction();
this.dbActor.setEmail(email);
this.dbActor.setCredential(psw);
manager.persist(this.dbActor);
ex.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new ActorException(CODE.UNKNOWN, e);
} finally {
manager.close();
}
}
现在我将下面的代码更改为从服务层开始事务,它看起来效率不高,还有其他写法吗?谢谢
private void internalCreateActor(String email, String psw) throws ActorException {
if (StringUtils.isEmpty(email) || StringUtils.isEmpty(psw))
throw new ActorException(CODE.INVALIDE_PARAMETER);
try {
this.dbActor.setEmail(email);
this.dbActor.setCredential(psw);
this.dbActor.setCreateD(new Date());
JPA.em().persist(this.dbActor);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new ActorException(CODE.UNKNOWN, e);
}
}
public void createActor(final String email, final String psw, final String cellPhone, final Actor.TYPE type)
throws Throwable {
JPA.withTransaction(new Callback0() {
@Override
public void invoke() throws Throwable {
internalCreateActor(email, psw, cellPhone, type);
}
});
}