保存具有@OneToMany关系的实体时,JPA2 NullPointerException [英] JPA2 NullPointerException when saving entities with @OneToMany relationship

查看:155
本文介绍了保存具有@OneToMany关系的实体时,JPA2 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two entities with @OneToMany relationship. Problem is I get a null pointer on the line getComps().add(comp) during save. It works fine if I explicitly instantiate the comps set. As you may know, this is not required if you have the annotations. I have other objects in that entity which work fine without explicit instantiation. What are the possible causes?

//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;

推荐答案

异常原因在代码中

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;
}

这篇关于保存具有@OneToMany关系的实体时,JPA2 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆