hi all,
i am about to use Hibernate as persistence layer for my application.
My app is a Struts-based application which is made of a set of Action class.
There is a 'Persistence Layer' in my app, represented by a PersistenceManager interface, which has ServletContext scope (only 1 instance will be created during whole application).
My concern were Hibernate Session handling... so i wanted to post my code to see if it was a proper approach in a J2EE application..
I am using ThreadLocal inside my PersistenceManager, and i am opening and closing session every time the PersistenceManager is used to insert/delete/update/or retrieve data..
can anyone tell me if there's something missing or something to be modified?
thanx in advance and regards
marco
Here is the code
class HibernatePersistenceManager implements PersistenceManager {
private String _configFilePath = "/hibernate.cfg.xml";
private SessionFactory _factory = null;
private static final ThreadLocal session = new ThreadLocal();
HibernatePersistenceManager() throws Exception{
_log.debug("Creating HibernatePM..");
}
private void initHibernate() throws Exception {
Configuration configuration = null;
URL configFileURL = null;
ServletContext context = null;
try {
configFileURL = HibernatePersistenceManager.class.getResource(_configFilePath);
_log.debug("Initializing Hibernate from "
+ _configFilePath + "...");
configuration = (new Configuration()).configure(configFileURL);
_factory = configuration.buildSessionFactory();
_log.debug("Simple Test....creatingp ersistent expense.....");
} catch (Throwable t) {
_log.error("Exception while initializing Hibernate.");
_log.error("Rethrowing exception...", t);
throw (new Exception(t));
}
}
public void insert(Entry data) throws PersistenceException {
try {
Session s = openSession();
HibernateEntry entry = (HibernateEntry)data;
Transaction t = s.beginTransaction();
s.save(entry);
t.commit();
closeSessions();
} catch(Exception e) {
_log.error("Exception in creating CastorEntry\n" + e);
throw new PersistenceException(e);
}
}
/**
* @return an Hibernate Session
*/
Session openSession() throws Exception {
Session s = (Session)session.get();
if(s== null) {
s = _factory.openSession();
session.set(s);
}
return s;
}
/**
* Closes an Hibernate Session
*/
void closeSession() throws Exception {
Session s = (Session)session.get();
session.set(null);
if(s != null)
s.close();
}
|