Duplicate records with Onetomany relationship

Asked

Viewed 895 times

6

I have a map 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 rescue service:

objetoClasseA.getListaClasseB().add(objetoClasseB);

And is made the persist or the merge only of objetoClasseA.

When adding a objetoClasseB, two records of the same are saved, even with the list containing only 1 element.

What reasons could lead to duplicate records?

1 answer

3


This may be happening for some of the reasons below:

  1. You are using Detached objects in listObjetosB. JPA isn’t always smart enough to understand that it should create or update the objectClasseB contained in listing. In other words, instantiating a new objectClasseB with all attributes filled does not guarantee that JPA will know exactly what to do with it.
  2. Misuse of the Cascade I don’t know if you used Cascade in Classeb mapping. If you used this can give you trouble, then I suggest you evaluate the need. I only use Calendar in the main entities (which contains the list).

If it is none of the cases I ask you to include more details in your question.

EDIT

It is very important to understand the persist and the merge

The persist takes the instance of the entity and includes it in context. From this moment on, any changes made will be reflected.

The merge copies the state of your entity to a new instance and includes this instance in the context. No subsequent changes to the original entity will be reflected unless you call merge again.

In most cases there is not much point in making a persist accompanied by a merge, especially when using JTA.

  • I put the way the mapping is done in class B. There is no use of Scade. I believe not the case of objects Detached, as I am testing only with the empty list, adding a single objetoClasseB. What I’ve just noticed is that by persisting objetoClasseA, containing a objetoClasseB, the problem does not occur. When merging in the same situation, the problem manifests itself. There is some problem in instantiating the list in the Classea constructor ?

  • So I recommend that you set the Scades correctly. Using the default values can cause this kind of problem.

  • The Scade merge was the problem. I only left persist and delete. What I don’t understand is why the merge saves duplicate records and persist does not.

  • @user1902062 slightly improved my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.