Marcos J.C Kichel Marcos J.C Kichel - 1 year ago 48
Java Question

JPA - Reload @OneToMany dependencies automatically

I have this scenario:

public abstract class AbstractEntity {
@Id @GeneratedValue(strategy = GenerationType.TABLE)
protected Long id;

public class User extends AbstractEntity {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Dependent> dependents;

public class Dependent extends AbstractEntity {
private User user;

When I try to
a new
instance with some
's that already are present in database, what means they have the
field populated, I get a
Detached entity passed to persist

It can be solved by manually loading all the
s from database, but it don't look right.

I would like to know how to make JPA automatically load them when
field is populated. How can I do that?

Answer Source

If you are using JPA API use:

EntityManager.merge(T t)

instead of

EntityManager.persist(Object object)

Since you are using CascadeType.ALL, when you use merge, the JPA Provider will try to update the Users (in case they exists in database) or will create new ones.