6 Replies Latest reply on Oct 23, 2013 2:40 AM by kozachuk-v

    EntityManager not injected

    kgoedert

      Hi,

       

      I am trying to create a simple jpa test following the example suggested here http://arqpreview-alrubinger.rhcloud.com/guides/testing_java_persistence/index.html#run_the_test_jboss_as

       

      I am using jboss 6.1.0.final. I can tun the test, A war file is created correctly, using my test datasource, the tables are created in hsqldb, but when I try to use the entity manager it is always null.

       

      The test is as follows:

       

       

      {code}

      package com.sample.domain;

       

       

      import java.io.Serializable;

       

       

      import javax.persistence.Column;

      import javax.persistence.Entity;

      import javax.persistence.GeneratedValue;

      import javax.persistence.GenerationType;

      import javax.persistence.Id;

      import javax.validation.constraints.NotNull;

       

       

      @Entity

      public class User implements Serializable{

                private static final long serialVersionUID = 1L;

       

       

                @Id

                @GeneratedValue(strategy = GenerationType.AUTO)

                @Column(name = "id", updatable = false, nullable = false)

                private Long id;

       

                @Column(name = "name")

                @NotNull

                private String name;

       

       

                public Long getId() {

                          return id;

                }

       

       

                public void setId(Long id) {

                          this.id = id;

                }

       

       

                public String getName() {

                          return name;

                }

       

       

                public void setName(String name) {

                          this.name = name;

                }

       

                @Override

                public boolean equals(Object that) {

                          if (this == that) {

                                    return true;

                          }

                          if (that == null) {

                                    return false;

                          }

                          if (getClass() != that.getClass()) {

                                    return false;

                          }

                          if (id != null) {

                                    return id.equals(((User) that).id);

                          }

                          return super.equals(that);

                }

       

       

                @Override

                public int hashCode() {

                          if (id != null) {

                                    return id.hashCode();

                          }

                          return super.hashCode();

                }

       

                public String toString() {

                          return name;

                }

      }

      {code}

       

       

      and the test class

       

       

      {code}

      package com.sample.domain;

       

       

      import static org.junit.Assert.assertEquals;

      import static org.junit.Assert.assertTrue;

       

       

      import java.util.Arrays;

      import java.util.Collection;

      import java.util.HashSet;

      import java.util.List;

      import java.util.Set;

       

       

      import javax.inject.Inject;

      import javax.persistence.EntityManager;

      import javax.persistence.PersistenceContext;

      import javax.transaction.UserTransaction;

       

       

      import org.jboss.arquillian.container.test.api.Deployment;

      import org.jboss.arquillian.junit.Arquillian;

      import org.jboss.shrinkwrap.api.Archive;

      import org.jboss.shrinkwrap.api.ShrinkWrap;

      import org.jboss.shrinkwrap.api.asset.EmptyAsset;

      import org.jboss.shrinkwrap.api.spec.WebArchive;

      import org.junit.After;

      import org.junit.Before;

      import org.junit.Test;

      import org.junit.runner.RunWith;

       

       

      @RunWith(Arquillian.class)

      public class UserPersistenceTest {

       

       

                @PersistenceContext(name="sample-default")

                EntityManager em;

       

                @Inject

          UserTransaction utx;

       

                private static final String[] USER_NAMES = {

              "Joe Satriani",

              "Steve Vai",

              "Jeff Beck"

          };

       

                @Deployment

                public static Archive<?> createDeployment() {

                          return ShrinkWrap.create(WebArchive.class, "test.war").addPackage(User.class.getPackage()).addAsResource("test-persistence.xml", "META-INF/persistence.xml")

                                              .addAsWebResource(EmptyAsset.INSTANCE, "beans.xml");

                }

       

                @Before

                public void preparePersistenceTest() throws Exception {

                    clearDatabase();

                    insertData();

                    startTransaction();

                }

       

       

                private void clearDatabase() throws Exception {

                    utx.begin();

                    em.joinTransaction();

                    em.createQuery("delete from User").executeUpdate();

                    utx.commit();

                }

       

       

                private void insertData() throws Exception {

                    utx.begin();

                    em.joinTransaction();

                    for (String name : USER_NAMES) {

                        User user = new User();

                        user.setName(name);

                        em.persist(user);

                    }

                    utx.commit();

                }

       

       

                private void startTransaction() throws Exception {

                    utx.begin();

                    em.joinTransaction();

                }

       

                private static void assertContainsAllUsers(Collection<User> retrievedUsers) {

                    assertEquals(USER_NAMES.length, retrievedUsers.size());

                    final Set<String> retrievedUserNames = new HashSet<String>();

                    for (User user : retrievedUsers) {

                        retrievedUserNames.add(user.getName());

                    }

                    assertTrue(retrievedUserNames.containsAll(Arrays.asList(USER_NAMES)));

                }

       

       

                @After

                public void commitTransaction() throws Exception {

                    utx.commit();

                }

       

                @Test

                public void shouldFindAllUsersUsingJpqlQuery() throws Exception {

                    // given

                    String fetchingAllUsersInJpql = "select u from User u order by u.id";

       

       

                    // when

                    System.out.println("Selecting (using JPQL)...");

                    List<User> users = em.createQuery(fetchingAllUsersInJpql, User.class).getResultList();

       

       

                    // then

                    System.out.println("Found " + users.size() + " Users (using JPQL)");

                    assertContainsAllUsers(users);

                }

       

       

      }

       

      {code}

       

       

      The test-persistence is this

       

       

      {code}

      <?xml version="1.0" encoding="UTF-8"?>

      <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"

          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

          xsi:schemaLocation="

              http://java.sun.com/xml/ns/persistence

              http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

          <persistence-unit name="test">

              <jta-data-source>java:/DefaultDS</jta-data-source>

              <properties>

                  <property name="hibernate.hbm2ddl.auto" value="create-drop"/>

                  <property name="hibernate.show_sql" value="true"/>

              </properties>

          </persistence-unit>

      </persistence>

       

      {code}

       

      and my pom.xml

       

       

      {code}

      <?xml version="1.0" encoding="UTF-8"?>

      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

                <modelVersion>4.0.0</modelVersion>

                <groupId>sample</groupId>

                <artifactId>sample</artifactId>

                <version>0.0.1-SNAPSHOT</version>

                <packaging>war</packaging>

       

       

                <name>sample</name>

       

       

                <properties>

                          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

                          <arquillian.version>1.0.0.CR1</arquillian.version>

                          <jboss-javaee6-spec.version>1.0.0.Final</jboss-javaee6-spec.version>

                </properties>

       

       

       

       

       

       

                <profiles>

                          <profile>

                                    <id>jbossas-remote-6</id>

                                    <dependencies>

                                              <dependency>

                                                        <groupId>org.jboss.arquillian.container</groupId>

                                                        <artifactId>arquillian-jbossas-remote-6</artifactId>

                                                        <version>1.0.0.CR2</version>

                                              </dependency>

                                              <dependency>

                                                        <groupId>org.jboss.jbossas</groupId>

                                                        <artifactId>jboss-as-client</artifactId>

                                                        <version>6.1.0.Final</version>

                                                        <type>pom</type>

                                              </dependency>

                                    </dependencies>

                                    <build>

                                              <testResources>

                                                        <testResource>

                                                                  <directory>src/test/resources</directory>

                                                        </testResource>

                                                        <testResource>

                                                                  <directory>src/test/resources-jbossas-remote</directory>

                                                        </testResource>

                                              </testResources>

                                    </build>

                          </profile>

                </profiles>

       

       

                <dependencyManagement>

                          <dependencies>

                                    <dependency>

                                              <groupId>org.jboss.arquillian</groupId>

                                              <artifactId>arquillian-bom</artifactId>

                                              <version>1.0.0.CR7</version>

                                              <type>pom</type>

                                              <scope>import</scope>

                                    </dependency>

                                    <dependency>

                                              <groupId>org.jboss.spec</groupId>

                                              <artifactId>jboss-javaee-6.0</artifactId>

                                              <version>2.0.0.Final</version>

                                              <type>pom</type>

                                              <scope>import</scope>

                                    </dependency>

                                    <dependency>

                                              <groupId>org.hibernate</groupId>

                                              <artifactId>hibernate-entitymanager</artifactId>

                                              <version>3.6.6.Final</version>

                                              <scope>provided</scope>

                                    </dependency>

                          </dependencies>

                </dependencyManagement>

       

       

                <dependencies>

                          <dependency>

                                    <groupId>org.hibernate</groupId>

                                    <artifactId>hibernate-validator</artifactId>

                                    <version>4.1.0.Final</version>

                                    <type>jar</type>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.hibernate.javax.persistence</groupId>

                                    <artifactId>hibernate-jpa-2.0-api</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.jboss.spec.javax.ejb</groupId>

                                    <artifactId>jboss-ejb-api_3.1_spec</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.jboss.spec.javax.transaction</groupId>

                                    <artifactId>jboss-transaction-api_1.1_spec</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>javax.enterprise</groupId>

                                    <artifactId>cdi-api</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.jboss.spec.javax.annotation</groupId>

                                    <artifactId>jboss-annotations-api_1.1_spec</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.jboss.spec.javax.servlet</groupId>

                                    <artifactId>jboss-servlet-api_3.0_spec</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.jboss.spec.javax.faces</groupId>

                                    <artifactId>jboss-jsf-api_2.0_spec</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.hibernate</groupId>

                                    <artifactId>hibernate-entitymanager</artifactId>

                                    <scope>provided</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.primefaces</groupId>

                                    <artifactId>primefaces</artifactId>

                                    <version>3.0</version>

                          </dependency>

                          <dependency>

                                    <groupId>org.glassfish</groupId>

                                    <artifactId>javax.faces</artifactId>

                                    <version>2.1.6</version>

                          </dependency>

                          <dependency>

                                    <groupId>junit</groupId>

                                    <artifactId>junit</artifactId>

                                    <version>4.8.2</version>

                                    <scope>test</scope>

                          </dependency>

                          <dependency>

                                    <groupId>org.jboss.arquillian.junit</groupId>

                                    <artifactId>arquillian-junit-container</artifactId>

                                    <scope>test</scope>

                          </dependency>

                </dependencies>

       

       

                <pluginRepositories>

                          <pluginRepository>

                                    <id>JBoss Repo</id>

                                    <url>https://repository.jboss.org/nexus/content/repositories/releases</url>

                                    <name>JBoss Repo</name>

                          </pluginRepository>

                </pluginRepositories>

       

       

                <repositories>

                          <repository>

                                    <id>JBOSS_NEXUS</id>

                                    <url>http://repository.jboss.org/nexus/content/groups/public</url>

                          </repository>

                          <repository>

                                    <id>maven-nuxeo</id>

                                    <name>Maven Nuxeo Repository</name>

                                    <url>https://maven.nuxeo.org/nexus/content/groups/public/</url>

                                    <layout>default</layout>

                                    <releases>

                                              <enabled>true</enabled>

                                              <updatePolicy>never</updatePolicy>

                                    </releases>

                                    <snapshots>

                                              <enabled>true</enabled>

                                              <updatePolicy>never</updatePolicy>

                                    </snapshots>

                          </repository>

                          <repository>

                                    <id>Prime Technology Maven Repository</id>

                                    <url>http://repository.primefaces.org</url>

                          </repository>

                </repositories>

       

       

                <build>

                          <finalName>sample2</finalName>

                          <plugins>

                                    <plugin>

                                              <groupId>org.apache.maven.plugins</groupId>

                                              <artifactId>maven-compiler-plugin</artifactId>

                                              <version>2.3.2</version>

                                              <configuration>

                                                        <source>1.6</source>

                                                        <target>1.6</target>

                                              </configuration>

                                    </plugin>

                                    <plugin>

                                              <groupId>org.apache.maven.plugins</groupId>

                                              <artifactId>maven-war-plugin</artifactId>

                                              <extensions>false</extensions>

                                              <version>2.1.1</version>

                                              <configuration>

                                                        <failOnMissingWebXml>false</failOnMissingWebXml>

                                              </configuration>

                                    </plugin>

                          </plugins>

                </build>

      </project>

       

      {code}

       

       

      What is wrong in the configuration files or test? Can anybody help?

       

      Thanks

       

      Kelly

        • 1. Re: EntityManager not injected
          kgoedert

          Just adding, when I pasted the code above on the entitymanager the unit name is wrong, it is supposed to be 'test'. I pasted it wrong. Even fixing the error persists

          • 2. Re: EntityManager not injected
            ddbear

            I have similar problem. If I create with ShrinkWrap a JavaArchive, EntityManager can be injected with @PersistenceContext annotation. But if i create an EnterpriseArchive, that contains my JavaArchive which should be tested and an other JavaArchive, EntityManager can not be injected in the test case instance.

             

            Maybe it is helpful to say, that in the case of JavaArchive I can inject beans in the test case instance using the @EJB annotation. But in the case of EnterpriseArchive it is possible only with @Inject annotation.

             

            I hope that somebody can help us.

            • 3. Re: EntityManager not injected
              dmatej

              EJB bean is injected, but entity manager not. I don't know why ...?

               

                @EJB(mappedName = "java:global/xxx-ear/xxx-ejb/XxxImpl")
                private Xxx service;
              
                @PersistenceContext(unitName = "xxx")
                private EntityManager manager;
              

               

              Inside the XxxImpl class is the entity manager injected correctly, but in this test instance is is always null.

              • 4. Re: EntityManager not injected
                kozachuk-v

                Correct early

                percistence.xml

                    persistence-unit name="test"

                in bean

                     @PersistenceContext(unitName="test")          

                     EntityManager em;

                • 5. Re: EntityManager not injected
                  aslak

                  You're not adding the beans.xml to the correct location in the WebArchive.

                   

                  It should be; addAsWebInfResource..

                  1 of 1 people found this helpful
                  • 6. Re: EntityManager not injected
                    kozachuk-v

                    I see what you create <persistence-unit name="test"> (in persistence.xml) and request

                    @PersistenceContext(name="sample-default") in class UserPersistenceTest. if you have them not two.