KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > services > database > impl > HibernateServiceImpl


1 /***************************************************************************
2  * Copyright 2001-2003 The eXo Platform SARL All rights reserved. *
3  * Please look at license.txt in info directory for more license detail. *
4  **************************************************************************/

5 package org.exoplatform.services.database.impl;
6
7 import java.io.Serializable JavaDoc;
8 import java.net.URL JavaDoc;
9 import java.sql.Connection JavaDoc;
10 import java.sql.PreparedStatement JavaDoc;
11 import java.util.*;
12 import net.sf.hibernate.*;
13 import net.sf.hibernate.cfg.Configuration;
14 import net.sf.hibernate.dialect.Dialect;
15 import org.apache.commons.logging.Log;
16 import org.exoplatform.services.database.DatabaseService;
17 import org.exoplatform.services.database.HibernateService;
18 import org.exoplatform.services.database.ObjectQuery;
19 import org.exoplatform.services.log.LogService;
20 import org.exoplatform.commons.exception.ObjectNotFoundException;
21 import org.exoplatform.container.configuration.*;
22
23 /**
24  * Created by The eXo Platform SARL .
25  * @author Tuan Nguyen tuan08@users.sourceforge.net
26  * Date: Jun 14, 2003
27  * @author dhodnett
28  * $Id: HibernateServiceImpl.java,v 1.3 2004/10/30 02:27:52 tuan08 Exp $
29  */

30 public class HibernateServiceImpl implements HibernateService {
31     
32     private SessionFactory factory_ ;
33     private Configuration config_ ;
34     private ThreadLocal JavaDoc threadLocal_ ;
35     private Log log_ ;
36   private DatabaseService dbservice_ ;
37   private String JavaDoc serviceName_ ;
38   private String JavaDoc datasource_ ;
39     
40   public HibernateServiceImpl(DatabaseService dbService, LogService lservice) {
41     log_ = lservice.getLog(getClass());
42     dbservice_ = dbService ;
43     threadLocal_ = new ThreadLocal JavaDoc() ;
44   }
45   
46     public HibernateServiceImpl(DatabaseService dbService,
47                               LogService lservice,
48                               ConfigurationManager confService) throws Exception JavaDoc {
49         this(dbService, lservice) ;
50     ServiceConfiguration sconf = confService.getServiceConfiguration(HibernateService.class) ;
51     PropertiesParam param = sconf.getPropertiesParam("exo.hibernate.service") ;
52     Map properties = param.getProperties() ;
53     configure(param.getName(), properties) ;
54     }
55     
56     void configure(String JavaDoc name, Map properties) throws Exception JavaDoc {
57     serviceName_ = name ;
58       config_ = new Configuration() ;
59     datasource_ = (String JavaDoc) properties.get("hibernate.datasource.name") ;
60       String JavaDoc dbType = dbservice_.getDatabaseType(datasource_);
61       setDialect(config_, dbType);
62       Iterator i = properties.entrySet().iterator() ;
63       while(i.hasNext()) {
64         Map.Entry entry = (Map.Entry) i.next() ;
65         config_.setProperty((String JavaDoc)entry.getKey(), (String JavaDoc)entry.getValue()) ;
66       }
67     }
68
69   private void setDialect(Configuration config , String JavaDoc dbType){
70         if(DatabaseService.HSQL.equals(dbType)) {
71             config.setProperty(DIALECT_PROPERTY, "net.sf.hibernate.dialect.HSQLDialect");
72         } else if(DatabaseService.MYSQL.equals(dbType)) {
73             config.setProperty(DIALECT_PROPERTY, "net.sf.hibernate.dialect.MySQLDialect");
74         } else if(DatabaseService.DB2.equals(dbType)) {
75             config.setProperty(DIALECT_PROPERTY, "net.sf.hibernate.dialect.DB2Dialect");
76         } else if(DatabaseService.ORACLE.equals(dbType)) {
77             config.setProperty(DIALECT_PROPERTY, "net.sf.hibernate.dialect.Oracle9Dialect");
78         } else if(DatabaseService.POSTGRESQL.equals(dbType)) {
79             config.setProperty(DIALECT_PROPERTY, "net.sf.hibernate.dialect.PostgreSQLDialect");
80         } else if(DatabaseService.SQL_SERVER.equals(dbType)) {
81             config.setProperty(DIALECT_PROPERTY, "net.sf.hibernate.dialect.SQLServerDialect");
82         }
83     }
84   
85   public String JavaDoc getServiceName() { return serviceName_ ; }
86   
87     public Session openSession() throws Exception JavaDoc {
88         Session currentSession = (Session)threadLocal_.get() ;
89         if(currentSession == null) {
90       log_.debug("open new hibernate session in openSession()") ;
91             SessionFactory factory = getSessionFactory() ;
92             currentSession = factory.openSession();
93             threadLocal_.set(currentSession) ;
94         }
95         return currentSession ;
96     }
97     
98     public Session openNewSession() throws Exception JavaDoc {
99         Session currentSession = (Session)threadLocal_.get() ;
100         if(currentSession != null) {
101             closeSession(currentSession) ;
102         }
103     log_.debug("open new hibernate session in openSession()") ;
104         SessionFactory factory = getSessionFactory() ;
105         currentSession = factory.openSession();
106         threadLocal_.set(currentSession) ;
107         return currentSession ;
108     }
109     
110     public SessionFactory getSessionFactory() {
111         if (factory_ == null) {
112             synchronized(this) {
113                 try {
114                     factory_ = config_.buildSessionFactory(); // Hibernate2 init
115
} catch (Throwable JavaDoc t) {
116                     log_.error("HibernateServiceImpl: could not configure hibernate using: ", t) ;
117                 }
118             }
119         }
120         return factory_ ;
121     }
122     
123     public void closeSession(Session session) {
124         if (session == null) return ;
125         try {
126             session.close();
127       log_.debug("close hibernate session in openSession(Session session)") ;
128         } catch (Throwable JavaDoc t) { log_.error("Error: " , t) ; }
129     threadLocal_.set(null) ;
130     }
131     
132     public void closeSession() {
133         Session currentSession = (Session)threadLocal_.get() ;
134         if(currentSession != null) {
135             closeSession(currentSession) ;
136       log_.debug("close hibernate session in openSession()") ;
137         }
138     }
139     
140     public Object JavaDoc findExactOne(Session session, String JavaDoc query, String JavaDoc id) throws Exception JavaDoc {
141         List l = session.find(query, id, Hibernate.STRING);
142         if ( l.size() == 0) {
143             throw new ObjectNotFoundException("Cannot find the object with id: " + id);
144         } else if ( l.size() > 1) {
145             throw new Exception JavaDoc("Expect only one object but found" + l.size());
146         } else {
147             return l.get(0) ;
148         }
149     }
150     
151     public Object JavaDoc findOne(Session session, String JavaDoc query, String JavaDoc id) throws Exception JavaDoc {
152         List l = session.find(query, id, Hibernate.STRING);
153         if ( l.size() == 0) {
154             return null ;
155         } else if ( l.size() > 1) {
156             throw new Exception JavaDoc("Expect only one object but found" + l.size());
157         } else {
158             return l.get(0) ;
159         }
160     }
161   
162     public Object JavaDoc findOne(Class JavaDoc clazz, Serializable JavaDoc id) throws Exception JavaDoc {
163     Session session = openSession() ;
164     Object JavaDoc obj = session.get(clazz, id) ;
165     return obj ;
166   }
167   
168     public Object JavaDoc findOne(ObjectQuery q) throws Exception JavaDoc {
169     Session session = openSession() ;
170       List l = session.find(q.getHibernateQuery());
171     if ( l.size() == 0) {
172       return null ;
173     } else if ( l.size() > 1) {
174       throw new Exception JavaDoc("Expect only one object but found" + l.size());
175     } else {
176       return l.get(0) ;
177     }
178     }
179     
180   public Object JavaDoc create(Object JavaDoc obj) throws Exception JavaDoc {
181     Session session = openSession() ;
182     session.save(obj) ;
183     session.flush();
184     return obj ;
185   }
186   
187   public Object JavaDoc update(Object JavaDoc obj) throws Exception JavaDoc {
188     Session session = openSession() ;
189     session.update(obj) ;
190     session.flush();
191     return obj ;
192   }
193   
194   public Object JavaDoc save(Object JavaDoc obj) throws Exception JavaDoc {
195     Session session = openSession() ;
196     session.saveOrUpdateCopy(obj) ;
197     session.flush();
198     return obj ;
199   }
200   
201   public Object JavaDoc remove(Object JavaDoc obj) throws Exception JavaDoc {
202     Session session = openSession() ;
203     session.delete(obj) ;
204     session.flush();
205     return obj ;
206   }
207  
208   public Object JavaDoc remove(Class JavaDoc clazz , Serializable JavaDoc id) throws Exception JavaDoc {
209     Session session = openSession() ;
210     Object JavaDoc obj = session.get(clazz, id) ;
211     session.delete(obj) ;
212     session.flush() ;
213     return obj ;
214   }
215   
216   public Object JavaDoc remove(Session session ,Class JavaDoc clazz , Serializable JavaDoc id) throws Exception JavaDoc {
217     Object JavaDoc obj = session.get(clazz, id) ;
218     session.delete(obj) ;
219     return obj ;
220   }
221   
222     synchronized public void addMappingFiles(String JavaDoc[] path) {
223     closeSession() ;
224         ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader() ;
225         try {
226       Configuration temp = new Configuration() ;
227             for (int i = 0 ; i < path.length; i++) {
228                 URL JavaDoc url = cl.getResource(path[i]) ;
229                 config_.addURL(url) ;
230         temp.addURL(url) ;
231             }
232       createTables(temp) ;
233             if (factory_ != null) {
234                 factory_.close() ;
235                 factory_ = null ;
236             }
237         } catch (Throwable JavaDoc t) {
238             log_.error("HibernateServiceImpl: could not configure hibernate", t);
239         }
240     }
241     
242     private void createTables(Configuration config) throws Exception JavaDoc {
243         Dialect dialect = Dialect.getDialect(config_.getProperties()) ;
244         String JavaDoc[] script = config_.generateSchemaCreationScript(dialect) ;
245         for (int i = 0; i < script.length; i++) {
246             createTable(script[i]) ;
247         }
248     }
249     
250     private void createTable(String JavaDoc script) {
251     Connection JavaDoc conn = null ;
252         try {
253       conn = dbservice_.getDataSource(datasource_).getConnection();
254             PreparedStatement JavaDoc ps = conn.prepareStatement(script);
255             ps.executeUpdate();
256       conn.commit() ;
257       conn.close() ;
258         } catch (Exception JavaDoc ex) {
259             log_.info("Try create the table but fail. probably the table are already created");
260         } finally {
261       if(conn != null) {
262         try {
263          conn.close() ;
264         } catch(Exception JavaDoc ex) {
265           //log_.error(ex);
266
}
267       }
268     }
269     }
270 }
271
Popular Tags