JPA.em()。find为现有对象返回null

时间:2013-10-10 12:12:29

标签: java jpa nullpointerexception playframework-2.0 entitymanager

我在Play框架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();
}

你能告诉我为什么我从第二个查询查询中获得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)时,我得到了有效的用户对象。

0 个答案:

没有答案