我在播放框架 2.1 中遇到 JPA 问题。这是我的情况:
我有处理注册我的应用程序的操作方法(用户填写电子邮件和密码并提交表单)。在这种方法中,我检查用户是否存在于我的数据库中,如果不存在,则创建新用户。这是显示其工作原理的简化代码:
public Result signUpSubmit(String email, String password) {
User existingUser = (User) User.find("SELECT u FROM User u WHERE u.email=?", email).get(0);
if (existingUser != null) {
// code which handles existing user
} else {
User newUser = new User(email, password);
Users.persistUserAsync(newUser); // calls JPA.em().persist(newUser) asynchronously
// but I wait until the save is done
// After this call I have new row in DB with newUser (with assigned id)
System.out.println(newUser.id); // prints id which was assigned to new user in DB
User u = (User)JPA.em().find(User.class, newUser.id)
System.out.println(u.id); // throws NullPointer exception, because u is null
}
return renderJapid();
}
你能告诉我为什么我从第二个 find 查询中得到 null 的原因吗?
public boolean persistUserAsync(User) {
final ModelCreatingJob modelCreatingJob = new ModelCreatingJob(user);
final Promise<Boolean> promisedSave = modelCreatingJob.now();
final Boolean saved = promisedSave.get(20000L);
return saved;
}
ModelCreatingJob 只做这个:
return JPA.withTransaction(new F.Function0<Boolean>() {
@Override
public Boolean apply() throws UserLockedException, UserNotFoundException {
return model.validateAndCreate();
}
});
奇怪的是,当我在第二次查找时删除第一个查找(仅保留 newUser = null)时,我得到了有效的用户对象。