gpt4 book ai didi

java - 使用 Java 的 Playframeowk 抛出 JPA 事务失败。由: there is no started appliaction引起

转载 作者:行者123 更新时间:2023-12-01 09:29:39 25 4
gpt4 key购买 nike

我正在使用带有 Java 和 hibernate 的 Play 2.5.7。我需要进行一些数据库调用并在应用程序启动时加载配置。由于标题中的错误,它一直失败。代码、应用启动类:

public class ApplicationStart {
@Inject
public ApplicationStart(JPAApi jpaApi, ConfigService configService) {
jpaApi.withTransaction(() -> {
configService.reloadConfigs();
});
}
}

模块,配置方法:

bind(HibernateDao.class).to(HibernateDaoImpl.class);
bind(ConfigService.class).to(ConfigServiceImpl.class);
bind(ApplicationStart.class).asEagerSingleton();

配置服务Impl:

@Override
public void reloadConfigs() {
List<Implementation> impls = hibernateDao.executeQueryForObject(QUERY_GET_IMPLEMENTATIONS, null);
// process and load the condig.
}

HibernateDaoImpl:

@Override
public <T> List<T> executeQueryForObject(String sql, Map<String, Object> map)
throws PersistenceException {
EntityManager em = JPA.em("default");
try {
Query query = prepareQuery(em, sql, map);
List<T> objectList = query.getResultList();
return objectList;
} finally {
em.close();
}
}

实际错误:

play.api.UnexpectedException: Unexpected exception[CreationException: Unable to create injector, see the following errors:

1) Error injecting constructor, java.lang.RuntimeException: JPA transaction failed
...
Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:
...
Caused by: java.lang.RuntimeException: JPA transaction failed
...
Caused by: java.lang.RuntimeException: There is no started application
at scala.sys.package$.error(package.scala:27)
at play.api.Play$$anonfun$current$1.apply(Play.scala:86)
at play.api.Play$$anonfun$current$1.apply(Play.scala:86)
at scala.Option.getOrElse(Option.scala:121)
at play.api.Play$.current(Play.scala:86)
at play.api.Play.current(Play.scala)
at play.Play.privateCurrent(Play.java:89)
at play.Play.application(Play.java:22)
at play.db.jpa.JPA.jpaApi(JPA.java:48)
at play.db.jpa.JPA.em(JPA.java:60)

最佳答案

那是因为您使用的是静态JPA.em,而不是注入(inject)正确的类。像在 ApplicationStart 类中那样注入(inject)它,它应该可以工作

public class HibernateDaoImpl implements HibernateDao {

private final JPAApi JPA_API;

@Inject
public HibernateDaoImpl(JPAApi api) {
this.JPA_API = api;
}


// (...)

@Override
public <T> List<T> executeQueryForObject(String sql, Map<String, Object> map)
throws PersistenceException {
EntityManager em = JPA_API.em("default");
try {
Query query = prepareQuery(em, sql, map);
List<T> objectList = query.getResultList();
return objectList;
} finally {
em.close();
}
}
// (...)
}

关于java - 使用 Java 的 Playframeowk 抛出 JPA 事务失败。由: there is no started appliaction引起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com