7
votes

I'm using hibernate 4.2.4 with JPA and layz loading in a ManyToMany association. Object A is associated with @ManyToMany(targetEntity=B.class, fetch=FetchType.LAZY) and contrariwise. To get data from database I call the following (simplified) code:

try {
   session = cutSessionFactory.openSession();
   session.beginTransaction();
   List<IBO> result = session.createQuery(query).list();
   session.getTransaction().commit();
   return result;
catch{...}
finally{
   session.close;
}

Originally I used to let the connection open, cause if my application needs to do some lazy loading the session is still needed after the first call. But while this made my application freeze after some actions, I chanced to the previous strategy. Now everything works; no freezing, no problem with lazy loading. But if I load an entity, which has some children (that requieres lazy loading) the log says:

WARN - AbstractPersistentCollection: Unable to close temporary session used to load lazy collection associated to no session

followed by

2013-09-25 09:35:30 - INFO - BasicResourcePool: A checked-out resource is overdue, and will be destroyed: com.mchange.v2.c3p0.impl.NewPooledConnection@15f52a7
2013-09-25 09:35:30 - INFO - BasicResourcePool: Logging the stack trace by which the overdue resource was checked-out

It makes sense that hibernate is not closing the session (actually I thought there is a new request for lazy loading that uses a new session) an the connection pool recognizes there is an unused session. But in the end hibernate is fixing my "bad session handling".

So does anyone know a better way to handle sessions used with lazy loading?

1
did u find an answer? when u see this warning, does the connection (from c3p0) is closed? or is there a connection-pool leak?OhadR

1 Answers

0
votes

Of course we need to close the session otherwise application might not work properly.

Also we should try to keep nested object lazy for better performance and add mandatory joins.

If you need to access the child element you have to apply join in the query, so that the lazy object will get loaded eg:

class A{
      B b;
}

sql:

select * from A Left join B on A.bid = B.id