Question :
I have a mapping as follows:
public class ClasseA {
public ClasseA(){
listaClasseB = new ArrayList<ClasseB>;
}
@OneToMany(mappedBy = "xxxx", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<ClasseB> listaClasseB;
}
public class ClasseB {
@ManyToOne
@JoinColumn(name = "xxxxxxxxxxx", nullable = false)
private ClasseA objetoClasseA;
}
In the method of the service responsible for the rescue:
objetoClasseA.getListaClasseB().add(objetoClasseB);
And persist or merge is only done with objetoClasseA
.
When adding a objetoClasseB
, two records are saved, even with the list containing only 1 element.
What reasons could lead to duplicate records?
Answer :
This may be occurring for some of the reasons below:
If it is not any of the cases I ask you to include more details in your question.
EDIT
It’s very important to understand persist and merge
persist takes the instance of the entity and includes it in the context. From this moment, any changes made will be reflected.
Merge copies the state of your entity to a new instance and includes this instance in context. No subsequent changes to the original entity will be reflected unless you call merge again.
In most cases there is not much sense in making a persist with a merge , especially when using JTA.