[java] PersistenceContext EntityManager injection NullPointerException

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.

This question is related to java hibernate jpa jboss resteasy

The answer is


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.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to hibernate

Hibernate Error executing DDL via JDBC Statement How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory Disable all Database related auto configuration in Spring Boot Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] HikariCP - connection is not available Hibernate-sequence doesn't exist How to find distinct rows with field in list using JPA and Spring? Spring Data JPA and Exists query

Examples related to jpa

No converter found capable of converting from type to type How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Deserialize Java 8 LocalDateTime with JacksonMapper Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed How to beautifully update a JPA entity in Spring Data? JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory How to return a custom object from a Spring Data JPA GROUP BY query How to find distinct rows with field in list using JPA and Spring? What is this spring.jpa.open-in-view=true property in Spring Boot? Spring Data JPA and Exists query

Examples related to jboss

How to enable TLS 1.2 in Java 7 Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war" SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl PSQLException: current transaction is aborted, commands ignored until end of transaction block JBoss AS 7: How to clean up tmp? How to deploy a war file in JBoss AS 7? How to increase heap size for jBoss server JBoss default password HTTP response header content disposition for attachments PersistenceContext EntityManager injection NullPointerException

Examples related to resteasy

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy Java 8 LocalDate Jackson format Can not deserialize instance of java.util.ArrayList out of START_OBJECT token REST - HTTP Post Multipart with JSON PersistenceContext EntityManager injection NullPointerException