栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在jersey / hk2应用程序中正确配置EntityManager?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在jersey / hk2应用程序中正确配置EntityManager?

一种选择是不是创建一个新

EntityManagerFactory
EMFactory
(这是在请求范围内),您可以创建为一个单独的工厂
EntityManagerFactory
,然后就注射
EntityManagerFactory
EMFactory

public class EMFFactory implements Factory<EntityManagerFactory> {    private final EntityManagerFactory emf;    public EMFFactory (){        emf = Persistence.createEntityManagerFactory(persistenceUnit);    }    public EntityManagerFactory provide() {        return emf;    }    ...}public class EMFactory implements Factory<EntityManager> {    private final EntityManager em;    @Inject    public EMFactory (EntityManagerFactory emf){        em = emf.createEntityManager();    }    public EntityManager provide() {        return em;    }    ...}

还没有测试过确切的实现,但是应该看起来像这样。我以前使用过这种模式。

register(new AbstractBinder() {    @Override    public void configure() {      bindFactory(EMFFactory.class).to(EntityManagerFactory.class).in(Singleton.class);      bindFactory(EMFactory.class).to(EntityManager.class).in(RequestScoped.class);    }});

更新

关于上面的示例,需要注意的一件事是它不会清理资源,即

EntityManager
应该关闭资源。它不会自行关闭。有一个
dispose
在方法
Factory
类,我们需要重写,但是从我的经验,这是从来没有通过所谓的球衣。

我们可以做的就是将

EntityManager
[
CloseableService
] 添加到[ ] [1]

public class EMFactory implements Factory<EntityManager> {    private final EntityManagerFactory emf;    private final CloseableService closeService;    @Inject    public EMFactory (EntityManagerFactory emf, CloseableService closeService){        this.emf = emf;        this.closeService = closeService;    }    public EntityManager provide() {        final EntityManager em = emf.createEntityManager();        this.closeService.add(new Closeable(){ @Override public void close() {     em.close(); }        });        return em;    }    ...}

这样,

EntityManager
可以确保在请求结束时将其关闭。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449759.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号