Marcos J.C Kichel Marcos J.C Kichel - 6 months ago 15
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 {
@ManyToOne
@JoinColumn
private User user;
}


When I try to
insert()
a new
User
instance with some
Dependent
's that already are present in database, what means they have the
id
field populated, I get a
Detached entity passed to persist
exception.

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

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

Answer

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.

Documentation: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html.