Domanda

I have tables named Country, City and People. What can I prevent hibernate to save same people object? Here is my classes and the problem is when I try to save a country object, Hibernate tries to save or update same people objects as expected.(City's people object and Country's people object has same PK)

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

Classes;

class Country{

.....

@JoinColumn(.....)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private City city;


@JoinColumn(.....)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private People people;

}

class City{

....

@JoinColumn(.....)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private People people;

}

Here is my save method;

public void save(){

    ....


    getCurrentSession().saveOrUpdate(customer); //Hibernate session


 }
È stato utile?

Soluzione

2 solutions here :

  • Use merge instead of save
  • or remove save cascade annotation.

Using both save and save cascade basically tells Hibernate "please persist this new object along with all his relationships which are also new". You don't want that.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top