I'm having trouble persists the following entities:
@Entity
@Table(name="entityOne")
public class EntityOne implements Serializable {
@Id
@Column(name = "id", nullable = false)
private Integer id;
@OneToMany(fetch = FetchType.LAZY, mappedBy="entityOne")
private List<EntityTwo> entities;
}
@Entity
@Table(name="entityTwo")
public class EntityTwo implements Serializable {
@Id
@Column(name = "id", nullable = false)
private Integer id;
@Inject
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="entityOne", referencedColumnName="id")
private EntityOne entityOne;
}
In EntityOneDAO:
em.merge(entityOne);
And it is only persisted to EntityOne and not the list of EntityTwo ... How do I persist the list ?
Thanks all
You need to take care of both:
So EntityOne should Cascade Persist and Merge to EntityTwo:
As you can see, you should always initialize your collection classes to avoid unnecessary null checks.
And it's always better to add the following helper child adding utility in your parent classes (e.g. EntityOne)
Then you can simply call:
P.S.
Please remove the @Inject annotation from the EntityTwo class. Entities are not Components. And persist is much more efficient than merge, when you want to insert new entities.