I'm working with Java and ORM and i get the PersistentException:
org.orm.PersistentException: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
I have the following code:
public boolean Añadir_video_a_historial(Usuario_Registrado_BD user, Video_BD video) throws PersistentException{
Boolean res = false;
PersistentTransaction t=ventanas.Actividad10PersistentManager.instance().getSession().beginTransaction();
try {
Historial_BD historial = user.getTiene_un();
if(historial.contiene.size() < 10){
if(historial.contiene.contains(video)){
historial.contiene.remove(video);
historial.contiene.add(video);
}else{
historial.contiene.add(video);
}
}else{
while(historial.contiene.size() >= 10){
Video_BD[] listaV = historial.contiene.toArray();
historial.contiene.remove(listaV[0]);
}
historial.contiene.add(video);
}
res = Historial_BDDAO.save(historial);
t.commit();
}catch(Exception e) {
t.rollback();
}
return res;
}
I don't know why am i getting this exception, at the end I do commit or rollback. The error is in the line "res = Historial_BDDAO.save(historial);", this code is auto-generated by Visual Paradign. I have another methods and all of them have the same structure. What am i doing wrong?
This problem is caused by the Historial_BD object and Video_BD object are loaded in different sessions. To solve this problem you should either load both objects from same session. i.e. using app based session which having single session for your application, or using thread based session and load the objects from the same thread.
Alternatively you can use lock or reload the objects form current session using its ID.