01: package org.conform.hibernate;
02:
03: import org.hibernate.*;
04: import org.hibernate.Session;
05: import org.apache.commons.logging.LogFactory;
06:
07: import java.sql.SQLException;
08: import java.util.*;
09:
10: public class HibernateEnvironment {
11: private static org.apache.commons.logging.Log LOG = LogFactory
12: .getLog(HibernateEnvironment.class);
13:
14: protected static final ThreadLocal threadLocal = new ThreadLocal();
15:
16: public static HibernateEnvironment getInstance() {
17: return (HibernateEnvironment) threadLocal.get();
18: }
19:
20: public static void setInstance(HibernateEnvironment environment) {
21: threadLocal.set(environment);
22: }
23:
24: protected HibernateEnvironment() {
25: }
26:
27: private SessionFactory sessionFactory;
28: protected Transaction transaction;
29: protected boolean setRollbackOnly;
30:
31: public SessionFactory getSessionFactory() {
32: return sessionFactory;
33: }
34:
35: public void setSessionFactory(SessionFactory sessionFactory) {
36: this .sessionFactory = sessionFactory;
37: }
38:
39: public void beginTransaction() throws HibernateException {
40: System.out.println("HibernateEnvironment.beginTransaction "
41: + this );
42: setRollbackOnly = false;
43: Session session = sessionFactory.getCurrentSession();
44: transaction = session.beginTransaction();
45: }
46:
47: public void setSetRollbackOnly(boolean setRollbackOnly) {
48: LOG.debug("set rollback only");
49: this .setRollbackOnly = setRollbackOnly;
50: }
51:
52: public void endTransaction() throws HibernateException {
53: System.out.println("HibernateEnvironment.endTransaction "
54: + this );
55:
56: Session session = sessionFactory.getCurrentSession();
57: if (session == null)
58: return;
59: try {
60: if (setRollbackOnly) {
61: LOG.debug("rollback");
62: transaction.rollback();
63: } else {
64: LOG.debug("commit");
65: session.flush();
66: transaction.commit();
67: }
68: } catch (HibernateException e) {
69: transaction.rollback();
70: throw e;
71: } finally {
72: session.close();
73: }
74: }
75:
76: protected void ensureAutoCommitOff() throws HibernateException {
77: Session session = sessionFactory.getCurrentSession();
78: try {
79: boolean autoCommit = session.connection().getAutoCommit();
80: if (autoCommit) {
81: LOG.debug("session.connection().getAutoCommit() = "
82: + autoCommit);
83: session.connection().setAutoCommit(false);
84: }
85: } catch (SQLException e) {
86: throw new JDBCException("autocommit off", e);
87: }
88: }
89:
90: public void ensureTransactionClosed() {
91: if (transaction.isActive())
92: LOG.warn("Transaction still active");
93: }
94: }
|