1

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Shilpa
  • 98
  • 3
  • 19

3 Answers3

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>
Miljen Mikic
  • 14,765
  • 8
  • 58
  • 66
0

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

Tsonev
  • 435
  • 7
  • 17
0

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..

Alkanshel
  • 4,198
  • 1
  • 35
  • 54