Now I am using code tags .. hopefully it will keep the indentation ....
Code:
public Object findByPK( Class clazz, Serializable key ) throws DAOException, InvalidDataException {
Object result = null;
if ( null == key ) {
throw new InvalidDataException( "Attempted a find operation with a null key");
}
try {
Session session = HibernateUtil.getSession();
HibernateUtil.beginTransaction();
result = session.get( clazz, key );
HibernateUtil.commitTransaction();
} catch ( HibernateException he ) {
String message = "Failed to find [" + clazz.getName() + "] by primary key";
log.error( message, he );
HibernateUtil.rollbackTransaction();
throw new DAOException( message , he );
} finally {
HibernateUtil.closeSession();
}
return result;
}
------------------------------------
HibernateUtil code is as follows:
------------------------------------
Code:
public static Session getSession() throws DAOException {
Session s = (Session) threadSession.get();
// Open a new Session, if this thread has none yet
try {
if (s == null) {
s = sessionFactory.openSession();
s.setFlushMode( FlushMode.COMMIT );
threadSession.set(s);
log.debug( "Fetched session." );
} else {
log.debug( "Fetched pre-existing session." );
}
} catch (HibernateException ex) {
log.error("getSession", ex );
ex.printStackTrace();
throw new DAOException(ex);
}
return s;
}
public static void closeSession() throws DAOException {
try {
Session s = (Session) threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) {
log.debug( "Closing session." );
s.flush();
s.close();
}
} catch (HibernateException ex) {
log.error( "closeSession", ex );
ex.printStackTrace();
throw new DAOException(ex);
}
}
public static void beginTransaction() throws DAOException {
Transaction tx = (Transaction) threadTransaction.get();
try {
if (tx == null) {
tx = getSession().beginTransaction();
threadTransaction.set(tx);
log.debug( "Starting new transaction." );
} else {
log.debug( "Joining transaction in progress." );
}
} catch (HibernateException ex) {
log.error( "beginTransaction", ex );
ex.printStackTrace();
throw new DAOException(ex);
}
}
public static void commitTransaction() throws DAOException {
Transaction tx = (Transaction) threadTransaction.get();
try {
if ( tx != null && !tx.wasCommitted()
&& !tx.wasRolledBack() ){
tx.commit();
log.debug( "Commiting transaction." );
} else {
log.debug( "CommitTransaction called but no transaction was in progress." );
}
threadTransaction.set(null);
} catch (HibernateException ex) {
log.error( "commitTransaction", ex );
ex.printStackTrace();
rollbackTransaction();
throw new DAOException(ex);
}
}
Thanks
Ron