【问题标题】:EntityManager.find(MyClass.class, id) returns nullEntityManager.find(MyClass.class, id) 返回 null
【发布时间】:2014-12-26 10:43:58
【问题描述】:

我的 entitymanager.find() 给出了 nullpointerexception,数据库中有一行提供了 id。

@Entity
public class ForumCategory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column (name="title")
private String title;
@Column (name="datecreated")
private Date created;
@Column (name="dateupdated")
private Date updated;  
@Column (name="createdby")
private String createdBy;
@OneToMany(mappedBy="category")
private Set<ForumThread> threads;

这是查找方法

public ForumCategory find(Long id) {
    ForumCategory category = em.find(ForumCategory.class, id);
    return category;
}

我已经尝试使用但仍然错误。

em.createQuery("SELECT obj FROM ForumCategory obj WHERE obj.id=1")

我正在使用 MySqlWorkbench,当我运行“select * from forumcategory where id=1”时,它会返回正确的行。

【问题讨论】:

  • NPE 调用em.find 与该行不存在无关。 EntityManager 很可能为空。您将需要展示更多关于您的配置(persistence.xml、EntityManager - 您是否使用容器注入、自己创建)、运行时环境(即 stanalone、服务器)。由于某种原因,没有创建 EntityManager,如果是这种情况,则 EM 为空。同时发布堆栈跟踪。
  • 哦,我在 Netbeans 中使用调试器,但没有看到它。你是对的,它是空的,我会更深入地研究我的代码,试图找出错误所在。谢谢@peeskillet

标签: jakarta-ee jpa nullpointerexception entitymanager


【解决方案1】:

您的entityManagernull。这就是为什么在调用 em.find() 方法时会得到 NullPointerException 的原因。

【讨论】:

    猜你喜欢
    • 2013-04-29
    • 2019-06-16
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多