java.lang.NullPointerException in CreateNamedQuery

2019-08-15 18:13发布

问题:

I have the following code which is resulting in a java.lang.NullPointerException:

List results = em.createNamedQuery("User.findByUserName").setParameter("userName", username).getResultList();

User is the entity bean, which contains:

@NamedQuery(name = "User.findByUserName", query = "SELECT u FROM User u WHERE u.userName = :userName"),

Does anyone know why?

回答1:

A method getResultList() doesn't throw NullPointerException (it returns empty list if there's no match), so I'm guessing that it should be one of the following:

  • you didn't inject/initialize EntityManager em (did you forget @PersistenceContext annotation?)
  • String username is null

In case of EntityManager null, check whether you have persistence.xml file (it's mandatory!). It should look like:

<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="OEMSPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <jta-data-source>ADD JNDI NAME OF YOUR DATASOURCE, e.g. jdbc/sample</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>


回答2:

Try making it a Stateless Bean by adding @Stateless annotation above the public class. Worked for me.



回答3:

This can come about when your psql is referencing an entity property name. I was doing something like :param.user = x.user in my psql, but trying to grab the property "user" from a param (which hasn't been passed in yet when createQuery runs) was giving me the NPE. I wish this sort of thing were possible, though..