我有一个使用 JPA 持久性的 jersey-2 / hk2 应用程序。像这样在EntityManager
启动时绑定
public MyApplication() {
// ...
register(new AbstractBinder() {
@Override
public void configure() {
bindFactory(EmFactory.class)
.to(EntityManager.class)
.in(RequestScoped.class);
}
});
}
工厂类是
public class EmFactory implements Factory<EntityManager> {
private static final String PERSISTENCE_UNIT = "unit";
private EntityManagerFactory emf;
private CloseableService closeableService;
@Inject
public EmFactory(@Named(PERSISTENCE_UNIT) String persistenceUnit,
CloseableService closeableService) {
emf = Persistence.createEntityManagerFactory(persistenceUnit);
this.closeableService = closeableService;
}
@Override
public EntityManager provide() {
final EntityManager entityManager = emf.createEntityManager();
closeableService.add(new Closeable() {
@Override
public void close() throws IOException {
if(entityManager.isOpen()) {
entityManager.close();
}
}
});
return entityManager;
}
@Override
public void dispose(EntityManager entityManager) {
if(entityManager.isOpen()) {
entityManager.close();
}
}
}
这可行,但是对于每个请求,我都会在日志中收到有关 EntityManager 已注册的警告:
HHH000436: Entity manager factory name (unit) is already registered. \
If entity manager will be clustered or passivated, specify a unique \
value for property 'hibernate.ejb.entitymanager_factory_name'
我究竟做错了什么?在 jersey-2 / hk2 应用程序中初始化 EntityManager 的正确方法是什么?