Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate Play Framework JPA EntityManager最佳实践_Hibernate_Jpa_Orm_Playframework_Playframework 2.0 - Fatal编程技术网

Hibernate Play Framework JPA EntityManager最佳实践

Hibernate Play Framework JPA EntityManager最佳实践,hibernate,jpa,orm,playframework,playframework-2.0,Hibernate,Jpa,Orm,Playframework,Playframework 2.0,这是一个与最佳实践更相关的问题。我正在将Play Framework 2.2.1与JPA一起用于ORM持久化。Play提供了很多“helper”方法和类,特别是我发现的JPA.em()方法。但是,当我尝试在公共静态方法中使用此方法获取EntityManager对象时,会出现以下错误: RuntimeException: No EntityManager bound to this thread. Try to annotate your action method with @play.db.j

这是一个与最佳实践更相关的问题。我正在将Play Framework 2.2.1与JPA一起用于ORM持久化。Play提供了很多“helper”方法和类,特别是我发现的JPA.em()方法。但是,当我尝试在公共静态方法中使用此方法获取EntityManager对象时,会出现以下错误:

RuntimeException: No EntityManager bound to this thread. Try to annotate your action method with @play.db.jpa.Transactional
因为我是从静态方法调用JPA.em(),所以我想上面的错误是有道理的。我的问题是,创建EntityManager对象的最佳实践是什么?在应用程序生命周期内多次调用的静态方法内部执行类似操作来创建em对象是否成本高昂:

EntityManager em = Persistence.createEntityManagerFactory("DefaultDS").createEntityManager();
或者我应该创建对EntityManagerFactory的公共静态引用,并在静态方法中执行类似操作:

EntityManager em = staticEntityFactory.createEntityManager();
或者我应该在实体中创建一个em对象,并让每个实体像这样维护对em对象的引用吗

@Entity
public class myEntity {
   private static EntityManager em = Persistence.createEntityManagerFactory("DefaultDS").createEntityManager();
}

如果您能提供一些关于处理此问题的最佳方法的指导,我们将不胜感激,谢谢

我还在努力理解游戏的方方面面,因此我无法真正指导您进行最佳实践 但我认为,正如您所提到的错误,您必须向控制器方法添加@Transactionnal,从中从实体调用静态JPA方法,并在这些来自实体的静态方法中使用JPA.em()方法

比如:

@Entity
public class Account {
    ....
    public static Account getAccount(Long id) {
        return JPA.em().find(Account.class, id);
    }
}
在控制器中:

public class AccountService extends Controller{

@Transactional(readOnly = true)
public static Result getAccount(Long id){
    Account account = Account.getAccount(id);

    return ok(Json.toJson(account));
}
}

是的,你完全正确。通过使用@Transactional注释控制器,这修复了实体方法和静态方法的错误。谢谢你的榜样!希望这也能帮助其他人。