Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JPA2 in Tomcat 6: @PersitenceContext doesn't work, EntityManager is null

Tags:

jsf-2

jpa-2.0

I am using JSF2 with Pure JPA2. But the problem is with entityManager,

@PersistenceContext
private EntityManager entityManager;

Here entityManager is not getting injected and always null. Can some one please help me what is wrong in my code.

Here is my configuration.

User.java

    @Entity
    @Table(name="USER")
    public class User {

        private int id;
        private String name;
        private String surname;

        @Id
        @SequenceGenerator(name="user_id_seq_gen", sequenceName="USER_ID_GEN_SEQ", allocationSize=1)
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="user_id_seq_gen")
        @Column(name="ID", unique = true, nullable = false)
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Column(name="NAME", unique = true, nullable = false)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Column(name="SURNAME", unique = true, nullable = false)
        public String getSurname() {
            return surname;
        }

        public void setSurname(String surname) {
            this.surname = surname;
        }   

    }

persistence.xml

   <?xml version="1.0" encoding="UTF-8"?>
        <persistence 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" version="2.0">
           <persistence-unit name="testUnit" transaction-type="RESOURCE_LOCAL">
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <non-jta-data-source>java:/comp/env/testDS</non-jta-data-source>
              <class>com.user.external.test.User</class>
              <exclude-unlisted-classes>false</exclude-unlisted-classes>
              <properties>
                 <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
                 <property name="hibernate.max_fetch_depth" value="6"/>
                 <property name="hibernate.show_sql" value="false"/>
                 <property name="hibernate.format_sql" value="true"/>
              </properties>
           </persistence-unit>
        </persistence>

Tomcat Server.xml

    <Context docBase="usertools" path="/usertools" reloadable="true">
        <ResourceLink name="testDS" 
                  global="testDS"  
                  type="javax.sql.DataSource"/>
    </Context> 

TestBean.java

    @ManagedBean(name="testBean")
    @ViewScoped
    public class TestBean implements Serializable{

        @ManagedProperty("#{testService}")
        private ITestService testService;

        public void saveData(User user){
            testService.saveUser(user);
        }

        public void setTestService(ITestService testService){
            this.testService = testService;
        }

        public ITestService getTestService(){
            return testService;
        }
    }

TestServiceImpl.java

    @ManagedBean(name="testService")
    @ApplicationScoped
    public class TestServiceImpl implements ITestService {

        @ManagedProperty(value="#{testDAO}")
        private ITestDAO testDAO;

        public void saveUser(User user){
            testDAO.saveUser(user);
        }

        public void setTestDAO(ITestDAO testDAO){
            this.testDAO = testDAO;
        }

        public ITestDAO getTestDAO(){
            return testDAO;
        }

    }   

TestDao.java

    @ManagedBean(name = "testDAO")
    @ApplicationScoped
    public class TestDAO implements ITestDAO {

        @PersistenceContext
        private EntityManager entityManager; // is null

        public void saveUser(User user){
            entityManager.persist(user); // Getting Null Pointer Here....
        }   

        public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
        }

        public EntityManager getEntityManager() {
            return entityManager;
        }

    }

I have tried with @PersistenceContext name & unitName attributes. But still it is not working. Also tried with resource config in web.xml

    <persistence-context-ref>
            <persistence-context-ref-name>testUnit</persistence-context-ref-name>
            <persistence-unit-name>testUnit</persistence-unit-name>
        </persistence-context-ref>

        <resource-ref>
            <description>DB Connection</description>
            <res-ref-name>testUnit</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>

Still No Luck. Can some one please help me.

like image 297
uday Avatar asked Jun 29 '12 05:06

uday


People also ask

Which annotation can be used for injecting EntityManager?

You can use the @PersistenceContext annotation to inject an EntityManager in an EJB 3.0 client (such as a stateful or stateless session bean, message-driven bean, or servlet).

What happens if EntityManager is not closed?

If you don't close it your entities will be kept as attached, even after you're done using them. Your context will be kept alive even when you can no longer access your EM. The JPA Specification contains more details.

How do I get EntityManager from EntityManagerFactory?

Step 2: Obtaining an Entity Manager From a Factory EntityManager entityManager = entityManagerFactory. createEntityManager(); EntityManager — An EntityManager is an interface. createEntityManager() method — It creates a new application-managed EntityManager.

Is EntityManager an interface?

Interface EntityManager. Interface used to interact with the persistence context. An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.


1 Answers

Tomcat is not a Java EE container, so there are limitations related to container managed factories and dependency injection. Among others, you need to manually create the EntityManagerFactory and the EntityManager.

Hibernate documentation isn't clear on that, so here's the Eclipselink one: Tomcat/JPA tutorial. Check the "Limitations to JPA" section, this applies as good to Hibernate.

See also:

  • Best practice to get EntityManagerFactory
like image 138
BalusC Avatar answered Oct 13 '22 01:10

BalusC