在启动单例上使用 JPA
Using JPA on startup singleton
我想在启动时使用 JPA 2.1 eclipselink 访问数据库。当它运行时,我在控制台日志中登录成功,但它抛出 table 或视图不存在。但是,如果我通过休息服务在 servlet 中调用我的 dao,一切运行良好。我错过了什么吗?
public abstract class BaseDao {
@PersistenceContext(unitName = "myUnit")
protected EntityManager em;
public void create(Object entity);
public Ojbect get();
}
@Stateless
public class MyDaoService extends BaseDao {
@Override
public void create(Object entity) {
this.em.persit(entity);
}
// ...
}
@Singleton
@Startup
public class MySingleton{
@EJB
private MyDaoService service;
@Schedule(hours="*", minutes="*", seconds="*/30")
public void doSomething() {
MyEntity entity = new MyEntity();//assumed I have entity object
entity.setFirstName("firstName");
entity.setLastName("lastName");
service.create(entity); // >>>Table or view does not exist exception
}
}
如果您希望在 bean 初始化后调用 doSomething,则它需要 @PostConstruct。此外,如果您有依赖项,您需要在初始化该 bean 之前可用,那么您可以使用 @DependsOn
这解决了我的问题。
If a JEE and JTA managed entity manager is used, specifying a proxy user and password can be more difficult, as the entity manager and JDBC connection is not under the applications control. The persistence unit properties can still be specified on an EntityManager object as long as this is done before establishing a database connection. EclipseLink Solutions Guide for EclipseLink
编辑:确保在每次交易前设置它
我想在启动时使用 JPA 2.1 eclipselink 访问数据库。当它运行时,我在控制台日志中登录成功,但它抛出 table 或视图不存在。但是,如果我通过休息服务在 servlet 中调用我的 dao,一切运行良好。我错过了什么吗?
public abstract class BaseDao {
@PersistenceContext(unitName = "myUnit")
protected EntityManager em;
public void create(Object entity);
public Ojbect get();
}
@Stateless
public class MyDaoService extends BaseDao {
@Override
public void create(Object entity) {
this.em.persit(entity);
}
// ...
}
@Singleton
@Startup
public class MySingleton{
@EJB
private MyDaoService service;
@Schedule(hours="*", minutes="*", seconds="*/30")
public void doSomething() {
MyEntity entity = new MyEntity();//assumed I have entity object
entity.setFirstName("firstName");
entity.setLastName("lastName");
service.create(entity); // >>>Table or view does not exist exception
}
}
如果您希望在 bean 初始化后调用 doSomething,则它需要 @PostConstruct。此外,如果您有依赖项,您需要在初始化该 bean 之前可用,那么您可以使用 @DependsOn
这解决了我的问题。
If a JEE and JTA managed entity manager is used, specifying a proxy user and password can be more difficult, as the entity manager and JDBC connection is not under the applications control. The persistence unit properties can still be specified on an EntityManager object as long as this is done before establishing a database connection. EclipseLink Solutions Guide for EclipseLink
编辑:确保在每次交易前设置它