KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibatis > dao > engine > transaction > hibernate > HibernateDaoTransaction


1 /*
2  * Copyright 2004 Clinton Begin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.ibatis.dao.engine.transaction.hibernate;
17
18 import com.ibatis.dao.client.DaoException;
19 import com.ibatis.dao.engine.transaction.ConnectionDaoTransaction;
20 import net.sf.hibernate.HibernateException;
21 import net.sf.hibernate.Session;
22 import net.sf.hibernate.SessionFactory;
23 import net.sf.hibernate.Transaction;
24
25 import java.sql.Connection JavaDoc;
26
27 public class HibernateDaoTransaction implements ConnectionDaoTransaction {
28
29   private Session session;
30   private Transaction transaction;
31
32   public HibernateDaoTransaction(SessionFactory factory) {
33     try {
34       this.session = factory.openSession();
35       this.transaction = session.beginTransaction();
36     } catch (HibernateException e) {
37       throw new DaoException("Error starting Hibernate transaction. Cause: " + e, e);
38     }
39   }
40
41   public void commit() {
42     try {
43       try {
44         transaction.commit();
45       } finally {
46         session.close();
47       }
48     } catch (HibernateException e) {
49       throw new DaoException("Error committing Hibernate transaction. Cause: " + e);
50     }
51   }
52
53   public void rollback() {
54     try {
55       try {
56         transaction.rollback();
57       } finally {
58         session.close();
59       }
60     } catch (HibernateException e) {
61       throw new DaoException("Error ending Hibernate transaction. Cause: " + e);
62     }
63   }
64
65   public Session getSession() {
66     return session;
67   }
68
69   public Connection JavaDoc getConnection() {
70     try {
71       return session.connection();
72     } catch (HibernateException e) {
73       throw new DaoException("Error occurred getting connection from Hibernate Session. Cause: " + e, e);
74     }
75   }
76
77 }
78
Popular Tags