CreateNamedQuery中的java

CreateNamedQuery中的java

本文介绍了CreateNamedQuery中的java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,导致产生 java.lang.NullPointerException

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

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

用户是实体bean,其中包含:

User is the entity bean, which contains:

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

有人知道为什么吗?

推荐答案

方法 getResultList()不会抛出 NullPointerException (如果没有匹配项,则返回空列表),所以我我猜应该是以下其中之一:

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:


  • 您没有注入/初始化 EntityManager em (您是否忘了
    @PersistenceContext 批注?)

  • 字符串用户名为空

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

如果EntityManager为null,请检查是否具有persistence.xml文件(这是强制性的! )。看起来应该像这样:

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>

这篇关于CreateNamedQuery中的java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:13