Hi,
I have a little problem with my collection mapping I guess.
I have a bean class here which has a Collection (explicitly a Set) of another bean. If I remove/add entries in the collection I want to get everything updated in the database.
Code:
@Entity
@Table(name = "Subprograms")
public class Subprogram implements IEntity, Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "subprogram", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL)
private Set<SubprogramConfig> subprogramConfig = new HashSet<SubprogramConfig>();
public Subprogram() {
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Set<SubprogramConfig> getSubprogramConfigSet() {
return subprogramConfig;
}
public void setSubprogramConfigSet(Set<SubprogramConfig> SubprogramConfig) {
this.subprogramConfig = subprogramConfig;
}
}
Code:
@Entity
@Table(name = "Subprogram_config")
public class SubprogramConfig implements IEntity, Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "fk_subprogram")
private Subprogram subprogram;
public SubprogramConfig() {
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Subprogram getSubprogram() {
return subprogram;
}
public void setSubprogram(subprogram subprogram) {
this.subprogram = subprogram;
}
}
My Hibernate Manager Class does the following:
Code:
public static List<IEntity> executeUpdate(List<IEntity> entityList) {
session.beginTransaction();
entityList.forEach(entity -> {
Object persistentObj = session.load(entity.getClass(), entity.getId());
try {
BeanUtils.copyProperties(persistentObj, entity);
} catch (Exception e) {
e.printStackTrace();
}
session.save(persistentObj);
});
session.getTransaction().commit();
return entityList;
}
When I do some operations on the Collection now (adding and removing items) and save it with my Manager then I get the following error:
Exception in thread "Thread-2" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [main.java.controller.entities.SubprogramConfig#25]
What can I do to avoid this?
To say is that the IEntity in the list is a clone of the session object.