46

I have a war containing the following:

META-INF/MANIFEST.MF
WEB-INF/classes/META-INF/persistence.xml
WEB-INF/classes/com/test/service/TestServlet.class
WEB-INF/classes/com/test/service/TestEntity.class
WEB-INF/classes/jndi.properties
WEB-INF/classes/postgresql-ds.xml
WEB-INF/jboss-web.xml
WEB-INF/web.xml
index.jsp

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_1_0.xsd" version="1.0">
    <persistence-unit name="test">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/TestDS</jta-data-source>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

web.xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Test Web Application</display-name>

    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>
    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

    <resource-ref>
        <res-ref-name>TestDS</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
</web-app>

My TestServlet class is as follows:

package com.test.service;

import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;

@Path("/service")
public class TestService {

    @PersistenceContext(unitName = "test")
    private EntityManager em;

    @GET
    @Path("/get")
    @Produces("application/json")
    public List get() {
        return em.createQuery("from TestEntity").getResultList();
    }
}

When the get() method is invoked I get a NullPointerException; the EntityManager hasn't been injected. Any suggestions on what I might be missing or how I can diagnose it? There's very little in the server log.

I'm sure I had this working without the jboss-web.xml or the datasource entry in web.xml. I've deployed the ds.xml to the deploy directory separately too and that's definitely picked up - I can see it in the JMX console.

Tried using JBoss 4.2.3 and a 6.0 build with the same result.

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
rich
  • 18,987
  • 11
  • 75
  • 101
  • Guess there's problems with posting XML in code sections?! – rich Jan 16 '11 at 21:05
  • You would have to escape < and > ->< and > – adrianboimvaser Jan 16 '11 at 21:13
  • 4
    I've never tried it in practice, so don't pin me on it, but is it really possible to run JPA on a webapp which is been declared to run as Servlet 2.3 (J2EE 1.3) instead of Servlet 2.5 (Java EE 5, when JPA was introduced for first time)? – BalusC Jan 16 '11 at 22:17
  • Worth a try and wanted doing anyway, but updating to a 2.5 declaration didn't change the behaviour. – rich Jan 16 '11 at 22:48

3 Answers3

82

An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.

Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).

Here's an example of injecting an EntityManagerFactory:

package com.test.service;

import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;

@Path("/service")
public class TestService {

    @PersistenceUnit(unitName = "test")
    private EntityManagerFactory entityManagerFactory;

    @GET
    @Path("/get")
    @Produces("application/json")
    public List get() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            return entityManager.createQuery("from TestEntity").getResultList();
        } finally {
            entityManager.close();
        }
    }
}

The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.

Related question: Inject an EJB into JAX-RS (RESTful service)

Community
  • 1
  • 1
Andre Rodrigues
  • 2,214
  • 16
  • 14
  • 1
    Thanks, similar problem though in that I get an NPE on this line:
            EntityManager entityManager = entityManagerFactory.createEntityManager();
    
    – rich Jan 17 '11 at 21:21
  • Thanks, this worked for me! I'm using CXF 2.7.5, Hibernate 4.x, Spring 3.x, and JPA 2.x. – Kode Charlie Jul 15 '13 at 18:45
  • Please lemme know why I am not able to inject an entity manager in Stateless beans @PersistenceContext(unitName = "Tester2PU") private EntityManager em; in tomcat 7.0.27 is null. thanks senthil – user1503117 Aug 06 '14 at 13:06
  • @user1503117 hi, tomcat is not a EJB container. Please try TomEE or GlassFish or JBoss AS. – Evan Hu Dec 08 '14 at 11:01
  • 1
    @Andre: "An entity manager can only be injected in classes running inside a transaction". I don't think this is absolutely correct. You can inject an EXTENDED entity manager and use it in an non-transactional method and then call a transactional method and join the transaction (automatically or by calling EntityManager@joinTransaction()). – Mike Argyriou Jul 24 '15 at 09:14
  • Is this still true? – Jin Kwon Aug 05 '16 at 07:53
2

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
Bill Burke
  • 21
  • 1
0

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

J Slick
  • 929
  • 11
  • 17