EJB3 and manual hierarchy persistence

眉间皱痕 提交于 2019-12-03 09:11:12

Heh welcome to the hair-pulling that is JPA configuration.

In your case you have two choices:

  1. Manually persist the new object; or
  2. Automatically persist it.

To automatically persist it you need to annotate the relationship. This is a common one-to-many idiom:

@Entity
@Table(name = "PARENT_TABLE")
public class Parent {
  @Id private Long id;

  @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
  private Collection<Child> children;

  public void addChild(Child child) {
    if (children == null) {
      children = new ArrayList<Child>();
    }
    child.setParent(parent);
    children.add(child);
  }
}

@Entity
@Table(name = "CHILD_TABLE")
public class Child {
  @Id private Long id;

  @ManyToOne
  private Parent parent;

  public void setParent(Parnet parent) {
    this.parent = parent;
  }
}

Parent parent = // build or load parent
Child child = // build child
parent.addChild(child);

Because of the cascade persist this will work.

Note: You have to manage the relationship at a Java level yourself, hence manually setting the parent. This is important.

Without it you need to manually persist the object. You'll need an EntityManager to do that, in which case it is as simple as:

entityManager.persist(child);

At which point it will work correctly (assuming everything else does).

For purely child entities I would favour the annotation approach. It's just easier.

There is one gotcha I'll mention with JPA:

Parent parent = new Parent();
entityManager.persist(parent);
Child child = new Child();
parent.addChild(child);

Now I'm a little rusty on this but I believe that you may run into problems if you do this because the parent was persisted before the child was added. Be careful and check this case no matter what you do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!