5

Working with Wildfly 10 on the following: a JSON webservice accessing a postgresql db using hibernate through a DAO object.

More specifically, my POJO User.java:

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


    @Id @GeneratedValue
    @Column(name="id")
    private int id;

    @Column(name="username")
    private String userName;

    @Column(name="password")
    private String password;

    @Column(name="email")
    private String emailAddress;

    public User(String userName, String password, String emailAddress) {
        super();
        this.userName = userName;
        this.password = password;
        this.emailAddress = emailAddress;
    }

    public User() {
        super();
    }

    public int getId() {
        return id;
    }

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

My UserDao:

@Stateless
public class UserDao {

    @PersistenceContext (unitName="librarysoftjpa")
    private EntityManager entityManager;

    public List<User> getAllUsers(){
List<User> allUsers=null;

        CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
        CriteriaQuery<User> criteria = criteriaBuilder.createQuery(User.class);
        criteria.from(User.class);

        TypedQuery<User>query = entityManager.createQuery(criteria);
        allUsers = query.getResultList();
        return allUsers;    
    }
}

My webservice:

@RequestScoped
@Path("/users")
@Produces("application/json")
@Consumes("application/json")
public class UserWebService {


    private UserDao userDao;


    public UserWebService(){
        this.userDao=new UserDao();
    }
@GET
    @Path("/all")
    public List<User> getAllUsers(){
        List<User>users=this.userDao.getAllUsers();
        return users;
    }
}

My persistence.xml:

<persistence version="2.1"
   xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://xmlns.jcp.org/xml/ns/persistence
        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
   <persistence-unit name="librarysoftjpa" transaction-type="JTA">
    <jta-data-source>java:/PostGreLibrarySoftDS</jta-data-source>
    <class>org.declercq.librarysoftbackend.models.Permission</class>
    <class>org.declercq.librarysoftbackend.models.Role</class>
    <class>org.declercq.librarysoftbackend.models.User</class>
      <properties>
         <!-- Properties for Hibernate -->
         <property name="hibernate.hbm2ddl.auto" value="update" />
         <property name="hibernate.show_sql" value="true" />
         <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
         <property name="hibernate.format_sql" value="true"/>

      </properties>
   </persistence-unit>
</persistence>

So I'm using container managed persistence, managed by Wildfly 10. However, when accessing the webservice, I get a nullpointer exception for my entitymanager:

10:17:10,095 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 62) WFLYUT0021: Registered web context: /librarysoftbackend
10:17:10,174 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "librarysoftbackend.war" (runtime-name : "librarysoftbackend.war")
10:17:10,341 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
10:17:10,342 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
10:17:10,343 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 14178ms - Started 422 of 670 services (404 services are lazy, passive or on-demand)
10:17:18,898 ERROR [io.undertow.request] (default task-3) UT005023: Exception handling request to /librarysoftbackend/rest/users/all: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
    at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:77)
    at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:220)
    at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:175)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:418)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:209)
    at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.declercq.librarysoftbackend.dao.UserDao.getAllUsers(UserDao.java:64)
    at org.declercq.librarysoftbackend.rest.UserWebService.getAllUsers(UserWebService.java:69)
    at org.declercq.librarysoftbackend.rest.UserWebService$Proxy$_$$_WeldClientProxy.getAllUsers(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:139)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:295)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:249)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:236)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:402)
    ... 43 more

More specifically:

Caused by: java.lang.NullPointerException
    at org.declercq.librarysoftbackend.dao.UserDao.getAllUsers(UserDao.java:64)

Which points to:

CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();

in UserDao.java.

Any idea what I'm doing wrong here?

UPDATE: the topic linked here as possible duplicate has absolutely zero procent to do with this. My issue is with container managed persistence context and injecting an entitymanager in my application, not with not knowing how to initialize an object.

UPDATE2: I changed my code a bit and consider my UserDao as a Bean by adding the annotation @Stateless after reading this post from Adam Bien: http://www.adam-bien.com/roller/abien/entry/ejb_3_persistence_jpa_for. Basically states that DAO's are no longer needed for JPA, EJB's are better. However, still nullpointerexception on same location. (tried @Stateful too, same result).

UPDATE3: Configuration of my datasource in standalone.xml of Wildfly:

<datasources>
                <datasource jndi-name="java:/PostGreLibrarySoftDS" pool-name="PostgrePool">
                    <connection-url>jdbc:postgresql://127.0.0.1:5432/librarysoft</connection-url>
                    <driver>postgres</driver>
                    <security>
                        <user-name>test</user-name>
                        <password>test</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="postgres" module="org.postgres">
                        <driver-class>org.postgresql.Driver</driver-class>
                    </driver>
                </drivers>

Solved. The solution was to add @Stateless notation to my UserDao class, making it a bean. Next, in UserWebService, add the attribute:

@EJB
private UserDao userDao;

Injecting the bean here with @EJB was the solution.

aquilares
  • 311
  • 1
  • 6
  • 14
  • Have you initialized `entityManager` anywhere? You are getting nullpointer because it is not initialized – denvercoder9 Nov 12 '16 at 09:31
  • No, I don't initialize it anywhere. I was under the impression, since it's injected and managed by the application container, that I don't need to initialize it in my code? Where/how would I initialize it then? – aquilares Nov 12 '16 at 09:32
  • Lol, yeah thanks, but I kinda know what a Nullpointer exception is, why it occurs and how to fix it. My problem is with understanding the whole JPA/container managed persistence context and entity manager, not with "not knowing how to initialize an object" – aquilares Nov 12 '16 at 09:35
  • `org.declercq.librarysoftbackend.rest.UserWebService.getAllUsers(UserWebService.java:69)` – denvercoder9 Nov 12 '16 at 09:35
  • what's your point? That code calls the code I mentioned above (criteriabuilder creation) – aquilares Nov 12 '16 at 09:37
  • https://tomee.apache.org/examples-trunk/injection-of-entitymanager/README.html -> see the example here. I don't see any code that initializes the entitymanager after injecting it. I don't believe it's necessary to initialize it when using @PersistenceContext? – aquilares Nov 12 '16 at 09:40
  • Yup, you don't need to initialized it. I think the problem is with your query. – denvercoder9 Nov 12 '16 at 09:46
  • what kind of problem? What would the query have to do with it, since it gives a nullpointer exception on the first attempt at using the entitymanager? – aquilares Nov 12 '16 at 09:56

2 Answers2

0

Your UserDao is not managed by any framework. Please note that in the example you provided there's @Stateful on the Movies object. That tells you container that it should inject dependencies: PersistenceManager in your case.

Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
  • Yep, was just trying this too, I tried with Stateful and stateless for my UserDao, still same: nullpointerexception on same line. – aquilares Nov 12 '16 at 10:07
  • And how is your PostGreLibrarySoftDS configured? – Alexey Soshin Nov 12 '16 at 10:13
  • See original post please, just added my datasources config from Wildfly. – aquilares Nov 12 '16 at 10:16
  • First, in your current example you use Stateless, but you should be Stateful for anything to work. Second, in your persistence.xml, try PostGreLibrarySoftDS, since persistence.xml doesn't work with full JNDI names. – Alexey Soshin Nov 12 '16 at 10:21
  • Nope, sorry, changed to Stafeful and updated persistence.xml, still the same nullpointer exception. Are you sure about removing the java:/ too? Check the example here: https://docs.jboss.org/jbossas/docs/Server_Configuration_Guide/4/html/ch01s02s01.html – aquilares Nov 12 '16 at 10:26
  • Also, check this example: http://www.javawebtutor.com/articles/ejb/ejb3_and_jpa_example_in_eclipse.php, check the persistence.xml example, uses the java:/-prefix. – aquilares Nov 12 '16 at 10:35
  • Found the solution. See original post. I kept using the java:/ in persistence.xml. The solution was that I forgot to inject my UserDao bean (which is stateless by the way, not stateful) in my webservice class using the "@EJB" annotation. – aquilares Nov 12 '16 at 10:55
0

In your UserWebService resource, you are instantiating your UserDao as follows:

public UserWebService(){
     this.userDao=new UserDao();
}

Your UserDao is a @Stateless EJB (with a local no-interface view).

Therefore, let the EJB container inject the UserDao EJB as follows:

@EJB
private UserDao userDao;

You can now delete the UserWebService constructor.

I hope this helps.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228