Duplicate records with OneToMany relationship

6

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?

    
asked by anonymous 27.11.2014 / 13:11

1 answer

3

This may be occurring for some of the reasons below:

  • You are using detached objects in objectListB . JPA is not always smart enough to understand that it should create or update the ClassB object contained in ClassBase list . In other words, instantiating a newClasseB object with all of the filled attributes does not guarantee that JPA will know exactly what to do with it.
  • Misuse of Cascade I do not know if I used cascade in mapping in ClasseB. If you used this might give you a problem, so I suggest you evaluate the need. I just use cascade on the parent entities (which contains the list).
  • 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.

        
    27.11.2014 / 20:06