Hibernate: illegally attempted to associate a proxy with two open Sessions

20,092

Try closing proSess in getSeatByID() before returning. Currently the Seat indeed remains attached to session opened in getSeatByID().

Share:
20,092
Nima
Author by

Nima

Updated on July 09, 2022

Comments

  • Nima
    Nima almost 2 years

    I have 2 methods:

    public static Ticket issueTicket(User user,Service service,String[] seats) {
        Session ticSess= DB.factory.openSession();
        ticSess.beginTransaction();
        Date d= new Date();
        Ticket ticket=new Ticket(d, service, user);
    
        ticSess.save(ticket);
        ticSess.getTransaction().commit();
        int seatCount=seats.length;
        for (int i=0;i<seatCount;i++){
            int seatID=Integer.parseInt(seats[i]);
            Seat seat=getSeatByID(seatID);
            seat.setTicket(ticket);
            ticSess.update(seat);
        }
        return ticket;
    
    
    }
    

    and,

    public static Seat getSeatByID(int seatID) {
        Session proSess = DB.factory.openSession();
        proSess.beginTransaction();
        Seat c = (Seat) (proSess.load(Seat.class, seatID));
        proSess.getTransaction().commit();
    
        return c;
    }
    

    when I call issueTicket method I get:

    illegally attempted to associate a proxy with two open Sessions
    

    and If I close the session in getSeatByID method there will be another error telling that the session is closed. Here is the Stack Trace:

    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at ir.ac.shirazu.cse.Terminal.Seat_$$_javassist_9.setTicket(Seat_$$_javassist_9.java)
    at ir.ac.shirazu.cse.Database.DB.issueTicket(DB.java:231)
    
  • Nima
    Nima over 11 years
    If I close the session in getSeatByID method there will be another error telling that the session is closed.
  • Adam Dyga
    Adam Dyga over 11 years
    @Pishist Can you send full stacktrace of "closed session" exception? Maybe some lazy-initialization takes place at some point? Another thing is that I don't fully understand why you load the Seat in a separate session and transaction. You seem to open "transaction per DB operation" which is basically an anti-pattern.
  • Nima
    Nima over 11 years
    I think if I load the Seat in the same session the problem will be solved.Thanks. What should I do instead of transaction per DB operation? I heard that the transactions won't effect the database until we close them...
  • Adam Dyga
    Adam Dyga over 11 years
    @Pishist Read about unit of work here: docs.jboss.org/hibernate/orm/3.3/reference/en/html/…
  • Gaurav
    Gaurav about 5 years
    How do you deal with concurrency then?