我编写了两个注入服务的WebSocket ServerEndpoints,使用JPA EntityManager的注入实例与数据库进行交互。
该应用程序是部署在Tomcat服务器上的web应用程序,使用泽西岛作为JAX实现,Hibernate作为JPA提供程序。
有时,当试图在端点内访问DB时,EntityManager会被关闭。另外,我担心我可能已经生成了触发内存泄漏的代码。
这是我正在使用的自定义ServerEndpoint.Configurator (基于https://gist.github.com/facundofarias/7102f5120944c462a5f77a17f295c4d0):
public class Hk2Configurator extends ServerEndpointConfig.Configurator {
private static ServiceLocator serviceLocator;
public Hk2Configurator() {
if (serviceLocator == null) {
serviceLocator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
ServiceLocatorUtilities.bind(serviceLocator, new ServicesBinder()); // binds the "normal" Services that interact with the DB
ServiceLocatorUtilities.bind(serviceLocator, new AbstractBinder() {
@Override
protected void configure() {
bindFactory(EntityManagerFactory.class).to(EntityManager.class);
}
});
}
}
@Override
public <T> T getEndpointInstance(final Class<T> endpointClass) throws InstantiationException {
T endpointInstance = super.getEndpointInstance(endpointClass);
serviceLocator.inject(endpointInstance);
return endpointInstance;
}
}在应用程序的其余部分中,我使用的是相同的ServicesBinder,但是对于EntityManager使用的是不同的Binder。
EntityManagerFactory看起来如下所示:
public class EntityManagerFactory implements Factory<EntityManager> {
private static final javax.persistence.EntityManagerFactory FACTORY = Persistence.createEntityManagerFactory("PersistenceUnit");
@Override
public final EntityManager provide() {
return FACTORY.createEntityManager();
}
@Override
public final void dispose(final EntityManager instance) {
instance.close();
}
}RequestScoped (仅在那里,而不是在WebSocket端点中)加载了作用域。
我尝试为DAO中的每个访问创建一个EntityManager实例,但最后我会遇到org.hibernate.LazyInitializationExceptions,因为DTO需要一个开放的EntityManager (隐式)。
对如何绕过我的问题有什么建议吗?
发布于 2017-08-15 02:38:51
好的,我成功地解决了我的问题,每次我与数据库交互时,只要重写EntityManager处理就可以创建和关闭EntityManager。
https://stackoverflow.com/questions/45666129
复制相似问题