aspose file tools*
The moose likes Object Relational Mapping and the fly likes Question about a code snippet from book Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Question about a code snippet from book "beginning hibernate"" Watch "Question about a code snippet from book "beginning hibernate"" New topic
Author

Question about a code snippet from book "beginning hibernate"

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
I am reading the following code snippet from book "Bineginning Hibernate" by Dave Minter.

public class DAO {
private static final ThreadLocal session = new ThreadLocal();
private static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

public static Session getSession() {
Session session = (Session)DAO.session.get();
if(session == null) {
session = sessionFactory.openSession();
DAO.session.set(session);
}
return session;
}

public static void close() {
getSession().close(); // line 1
DAO.session.set(null);
}
....
....
}

The issue is from "close()" -- It calls "getSession()" first. Inside "getSession()", it checks if session is already null, if it is null, then it open a new session ! then it closes.. Is it necessary to open a session if the current one is null ?? Plus, should there be some exception handling for the "close()" (line 1) ??

I am thinking about modifying the "close() " method in the following way ---

public static void close() {
Session s = (Session)FWWDAO.session.get();
if(s != null && s.isOpen()) {
try {
s.close();
} catch (HibernateException e) {
log.error("DB can not close", e);
}
}
FWWDAO.session.set(null);
}

it first gets the session, if it is null or already closed, then skip it; if it is not null and open, we close it.

Does this make sense to you ??
Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
Could anybody help on this ?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about a code snippet from book "beginning hibernate"