因此,我目前正在使用 JPA 和 Hibernate 运行 Play Framework。我对这两者都是全新的,而且我在网上找到的教程超出了我的想象。
我到底如何发送简单的查询或创建表?这是我编写的示例代码,我得到:“RuntimeException:没有 EntityManager 绑定(bind)到此线程.尝试将此调用包装在 JPA.withTransaction 中,或确保在此线程上设置 HTTP 上下文。”
package controllers;
import play.Logger;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import play.db.jpa.JPA;
import play.mvc.Controller;
import play.db.*;
public class Database {
public static void initbuild() {
Logger.info("Checking database structure. The database will be restructured if not in the correct format.");
JPA.em().createQuery("create table test");
}
}
最佳答案
首先,您不想自己构建表,只需将模型写入模型包下,并通过 @Entity 注释它们,JPA 插件就会自动生成与您定义的模型匹配的表。 至于错误,引发错误是因为您应该使用 @Transactional 注释来注释该方法。 正如官方文档 http://www.playframework.com/documentation/2.3.x/JavaJPA 中所述 “每个 JPA 调用都必须在事务中完成,因此,要为特定操作启用 JPA,请使用 @play.db.jpa.Transactional 对其进行注释。这将使用为您管理事务的 JPA 操作来组合您的操作方法” 希望它有助于阅读文档并建议查看计算机-jpa 示例
关于java - 在 Play Framework 中使用 JPA/Hibernate 创建表/查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975896/