在Tomcat中使用生产者注入EntityManager [英] Injecting EntityManager with a producer in tomcat

查看:126
本文介绍了在Tomcat中使用生产者注入EntityManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在tomcat 7上运行一个使用Hibernate和Weld CDI的项目。我已经编写了一个ServletContextListener来在应用程序启动时创建EntityManagerFactory和EntityManager。

  public class PersistenceListener实现ServletContextListener {

private static EntityManagerFactory entityManagerFactory;

public void contextInitialized(ServletContextEvent sce){
ServletContext context = sce.getServletContext();
entityManagerFactory = Persistence.createEntityManagerFactory(hibernate-test);
}

public void contextDestroyed(ServletContextEvent sce){
entityManagerFactory.close();


$ b public static EntityManager createEntityManager(){
if(entityManagerFactory == null){
throw new IllegalStateException(Context尚未初始化。);
}

return entityManagerFactory.createEntityManager();
}

}

我可以使用我的entityManager测试类(它是一个arquillian测试类),只需通过以下代码创建它即可:


$ b $ pre $ EntityManager em = PersistenceListener.createEntityManager() ;
em.getTransaction()。begin();
em.createQuery(从游戏中删除)。executeUpdate();
em.getTransaction()。commit();

这里是我的测试类的完整代码

  @RunWith(Arquillian.class)
public class HibernateTestSample {

@Deployment
public static WebArchive createTestArchive()
{
MavenDependencyResolver解析器= DependencyResolvers.use(
MavenDependencyResolver.class).loadMetadataFromPom(pom.xml);

WebArchive webArchive = ShrinkWrap
.create(WebArchive.class,ROOT.war)
.addClasses(CdiTestBean.class,HibernateListener.class,PersistenceListener.class)
.addAsLibraries(
resolver.artifact(org.jboss.weld.servlet:weld-servlet)
// .artifact(org.hibernate.javax.persistence:hibernate-jpa-2.0 )
.artifact(org.apache.tomcat:tomcat-dbcp)
.artifact(org.hibernate:hibernate-entitymanager)
.artifact(org。 hibernate:hibernate-validator)
.artifact(org.hibernate:hibernate-core)
.artifact(com.h2database:h2)
.artifact(mysql:mysql -connector-java)
.resolveAs(Gen ericArchive.class))

.addAsWebInfResource(EmptyAsset.INSTANCE,beans.xml)
.addAsWebInfResource(test-persistence.xml,classes / META-INF / persistence。 xml)
.addAsWebInfResource(hibernate.cfg.xml,classes / hibernate.cfg.xml)
// .addAsWebInfResource(context.xml,classes / META-INF / context.xml)
.addAsManifestResource(context.xml,context.xml)
.setWebXML(hibernate-web.xml);
System.out.println(webArchive.toString(true));

返回webArchive;


$ b @Test
public void myTest()
throws Exception {

EntityManager em = PersistenceListener.createEntityManager( );
em.getTransaction()。begin();
em.createQuery(从游戏中删除)。executeUpdate();
em.getTransaction()。commit();
...............
.......
...


}
}

但我想将我的entityManager注入到我的类中。我在其他文章中阅读了,我无法在我的课程中使用@PersistenceContext,因此我决定使用生产者来注入我的实体经理。但它不适用于我,请告诉我我在这里做错了什么(我在CDI中很新)



这里是我的新ServletContextListener

  public class PersistenceListener implements ServletContextListener {

private static EntityManagerFactory entityManagerFactory;

@Produces
私人EntityManager entityManager;

public void contextInitialized(ServletContextEvent sce){
ServletContext context = sce.getServletContext();
entityManagerFactory = Persistence.createEntityManagerFactory(hibernate-test);
createEntityManager();
}

public void contextDestroyed(ServletContextEvent sce){
entityManagerFactory.close();


$ b $ public void createEntityManager(){
if(entityManagerFactory == null){
throw new IllegalStateException(Context尚未初始化。 );
}

this.entityManager = entityManagerFactory.createEntityManager();
}

而我正在注入我的测试类中

  @Inject 
私人EntityManager em;

它是空的

解决方案

您的 createEntityManager 方法需要 @Produces ,而不是字段。


I am running a project using Hibernate and Weld CDI on tomcat 7. I have write a ServletContextListener to create the EntityManagerFactory and EntityManager during application startup.

public class PersistenceListener implements ServletContextListener {

     private static EntityManagerFactory entityManagerFactory;

     public void contextInitialized(ServletContextEvent sce){
     ServletContext context = sce.getServletContext();
     entityManagerFactory = Persistence.createEntityManagerFactory("hibernate-test");
     }

     public void contextDestroyed(ServletContextEvent sce) {
     entityManagerFactory.close();
     }


     public static EntityManager createEntityManager() {
            if (entityManagerFactory == null) {
                throw new IllegalStateException("Context is not initialized yet.");
            }

            return entityManagerFactory.createEntityManager();
        }

}

I can use my entityManager in my test class (it is an arquillian test class) simply by creating it through the following code

EntityManager em = PersistenceListener.createEntityManager();
               em.getTransaction().begin();
                   em.createQuery("delete from Game").executeUpdate();
                   em.getTransaction().commit();

here is the complete code for my test class

    @RunWith(Arquillian.class)
    public class HibernateTestSample {

           @Deployment
           public static WebArchive createTestArchive()
           {
               MavenDependencyResolver resolver = DependencyResolvers.use(
                        MavenDependencyResolver.class).loadMetadataFromPom("pom.xml");

               WebArchive webArchive=  ShrinkWrap
                    .create(WebArchive.class, "ROOT.war")
                    .addClasses(CdiTestBean.class,HibernateListener.class,PersistenceListener.class)
                    .addAsLibraries(
                                resolver.artifact("org.jboss.weld.servlet:weld-servlet")
//                              .artifact("org.hibernate.javax.persistence:hibernate-jpa-2.0-api")
                                .artifact("org.apache.tomcat:tomcat-dbcp")
                                .artifact("org.hibernate:hibernate-entitymanager")
                                .artifact("org.hibernate:hibernate-validator")
                                .artifact("org.hibernate:hibernate-core")   
                                .artifact("com.h2database:h2")
                                .artifact("mysql:mysql-connector-java")
                                .resolveAs(GenericArchive.class))

                    .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
                    .addAsWebInfResource("test-persistence.xml", "classes/META-INF/persistence.xml")
                    .addAsWebInfResource("hibernate.cfg.xml", "classes/hibernate.cfg.xml") 
//                  .addAsWebInfResource("context.xml", "classes/META-INF/context.xml")
                    .addAsManifestResource("context.xml", "context.xml")
                    .setWebXML("hibernate-web.xml");
              System.out.println(webArchive.toString(true));

              return webArchive;
           }


           @Test
           public void myTest()
                   throws Exception {                                                      

               EntityManager em = PersistenceListener.createEntityManager();
               em.getTransaction().begin();
                       em.createQuery("delete from Game").executeUpdate();
                   em.getTransaction().commit();
                  ...............
                      .......
                      ...


           }
    }

but I want to inject my entityManager to my class. I read in an other post that I cannot use @PersistenceContext in my class, therefor I decided to use a producer to inject my entity manager. but it doesn't work for my, please tell me what am i doing wrong here (I am quite new in CDI )

here is my new ServletContextListener

public class PersistenceListener implements ServletContextListener {

     private static EntityManagerFactory entityManagerFactory;

     @Produces
     private EntityManager entityManager;

     public void contextInitialized(ServletContextEvent sce){
     ServletContext context = sce.getServletContext();
     entityManagerFactory = Persistence.createEntityManagerFactory("hibernate-test");
     createEntityManager();
     }

     public void contextDestroyed(ServletContextEvent sce) {
     entityManagerFactory.close();
     }


     public void createEntityManager() {
            if (entityManagerFactory == null) {
                throw new IllegalStateException("Context is not initialized yet.");
            }

            this.entityManager =  entityManagerFactory.createEntityManager();
        }

and I am injecting in my testclass

@Inject
private EntityManager em;

It is null

解决方案

You need @Produces on your createEntityManager method, instead of the field.

这篇关于在Tomcat中使用生产者注入EntityManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆