【问题标题】:JPA2 NullPointerException when saving entities with @OneToMany relationship [closed]保存具有@OneToMany 关系的实体时出现 JPA2 NullPointerException [关闭]
【发布时间】:2013-06-04 17:49:26
【问题描述】:

我有两个具有@OneToMany 关系的实体。问题是我在保存期间在getComps().add(comp) 行上得到一个空指针。如果我显式实例化 comps 集,它工作正常。如您所知,如果您有注释,则不需要这样做。我在该实体中有其他对象,无需显式实例化即可正常工作。可能的原因是什么?

//Main Method    
public static void main(String argz[]){
  ....
  Message message = new Message();
  message.setMessage("Hello World!");
  Comp comp = new Comp();
  comp.setName(getName());
  message.addComp(comp);
  user.createMessage(message);
  User aUser =  userService.save(user);
}

//Message Entity
@JsonIgnore
@OneToMany(targetEntity = Comp.class,
                mappedBy="message",
                fetch=FetchType.LAZY, 
                cascade={CascadeType.All},
                orphanRemoval=true)
private Set<Comp> comps;

public void addComp(Comp comp){
    comp.setMessage(this);
    getComps().add(comp);
}

//Comp Entity       
@JsonIgnore
@JsonBackReference
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="message_id")
private Message message;

【问题讨论】:

  • 向我们展示您正在执行的代码。您的期望可能是错误的。
  • 我已经包含了我用于测试的测试器方法。见上文
  • 回答这样的问题不需要熟悉Hibernate。您正在实例化一个 Comps 集为 null 的 Message,然后您尝试将 Comp 添加到该集合中。 Hibernate 与您的错误没有任何关系。您不能在空引用上调用方法,仅此而已。你应该接受罗曼的回答。
  • 看看“私人收藏订单”这一行你看到实例化了吗? tinyurl.com/kom3hfr
  • 没有。所以呢? Hibernate 不是黑巫术。将它放在类路径中将不允许您在空引用上调用方法。在您链接到的文章中,您是否看到在使用 new 实例化 Customer 后访问订单集合的任何地方?您是否意识到 Hibernate 不能神奇地初始化它没有创建的对象的字段?作为记录,我在这里回答了 1462 个 Hibernate 问题,得分为 2031。你不认为我知道我在说什么吗?

标签: java hibernate spring-mvc jpa-2.0 one-to-many


【解决方案1】:

异常原因在代码中

private Set<Comp> comps;

改成

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "message")
private Set<Comp> comps = new HashSet<Comp>(0);

public Set<Comp> getComps() {
  return this.comps;
}

public void setComps(Set<Comp> comps) {
  this.comps = comps;
}

【讨论】:

    猜你喜欢
    • 2012-07-28
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多