KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > db > DotHibernate


1 package com.dotmarketing.db;
2
3 import java.io.Serializable JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.List JavaDoc;
6
7 import net.sf.hibernate.Query;
8 import net.sf.hibernate.Session;
9 import net.sf.hibernate.SessionFactory;
10 import net.sf.hibernate.cfg.Configuration;
11 import net.sf.hibernate.cfg.Mappings;
12
13 import com.dotmarketing.exception.DotRuntimeException;
14 import com.dotmarketing.util.Logger;
15
16 /**
17  *
18  * @author will & david (2005)
19  */

20 public class DotHibernate {
21     private static String JavaDoc dialect;
22     private static SessionFactory sessionFactory;
23
24     private static ThreadLocal JavaDoc sessionHolder = new ThreadLocal JavaDoc();
25
26     private Class JavaDoc thisClass;
27
28     private Query query;
29
30     private int maxResults;
31
32     private int firstResult;
33
34     private int t;
35
36     private static Mappings mappings;
37
38     private static final boolean useCache = true;
39
40     public DotHibernate(Class JavaDoc c) {
41         setClass(c);
42     }
43
44     public DotHibernate() {
45     }
46
47     public void setClass(Class JavaDoc c) {
48         thisClass = c;
49     }
50
51     public static String JavaDoc getTableName(Class JavaDoc c) {
52
53         return mappings.getClass(c).getTable().getName();
54     }
55
56     public static String JavaDoc getDialect(){
57         if (sessionFactory == null) {
58             buildSessionFactory();
59         }
60         return dialect;
61     }
62     public int getCount() {
63         getSession();
64         int i = 0;
65
66         try {
67             if (maxResults > 0) {
68                 query.setMaxResults(maxResults);
69             }
70             if (firstResult > 0) {
71                 query.setFirstResult(firstResult);
72             }
73
74             i = ((Integer JavaDoc) query.list().iterator().next()).intValue();
75         } catch (Exception JavaDoc e) {
76             Logger.error(this, "---------- DotHibernate: error on list ---------------", e);
77             handleSessionException();
78             // throw new DotRuntimeException(e.toString());
79
}
80
81         return i;
82     }
83
84     public void setFirstResult(int firstResult) {
85         this.firstResult = firstResult;
86     }
87
88     public void setMaxResults(int g) {
89         this.maxResults = g;
90     }
91
92     public void setParam(long g) {
93         query.setLong(t, g);
94         t++;
95     }
96
97     public void setParam(String JavaDoc g) {
98         query.setString(t, g);
99         t++;
100     }
101
102     public void setParam(int g) {
103         query.setInteger(t, g);
104         t++;
105     }
106
107     public void setParam(java.util.Date JavaDoc g) {
108         query.setTimestamp(t, g);
109         t++;
110     }
111
112     public void setParam(boolean g) {
113         query.setBoolean(t, g);
114         t++;
115     }
116
117     public void setParam(double g) {
118         query.setDouble(t, g);
119         t++;
120     }
121
122     public void setParam(float g) {
123         query.setFloat(t, g);
124         t++;
125     }
126
127     public void setParam(Object JavaDoc g) {
128         query.setEntity(t, g);
129         t++;
130     }
131
132     public void setQuery(String JavaDoc x) {
133         Session session = getSession();
134
135         try {
136             query = session.createQuery(x);
137             query.setCacheable(useCache);
138         } catch (Exception JavaDoc e) {
139             Logger.error(this, "---------- DotHibernate: error setting query ---------------", e);
140             handleSessionException();
141             // throw new DotRuntimeException(e.toString());
142
}
143     }
144
145     public void setSQLQuery(String JavaDoc x) {
146         Session session = getSession();
147
148         try {
149             query = session.createSQLQuery(x, getTableName(thisClass), thisClass);
150             query.setCacheable(useCache);
151         } catch (Exception JavaDoc e) {
152             Logger.error(this, "---------- DotHibernate: error setting query ---------------", e);
153             handleSessionException();
154             // throw new DotRuntimeException(e.toString());
155
}
156     }
157
158     /*
159      * hibernate delete object
160      */

161     public static void delete(Object JavaDoc obj) {
162         Session session = getSession();
163
164         try {
165             session.delete(obj);
166             session.flush();
167         } catch (Exception JavaDoc e) {
168             Logger.error(DotHibernate.class, "---------- DotHibernate: error on delete ---------------", e);
169             handleSessionException();
170             // throw new DotRuntimeException(e.toString());
171
}
172     }
173
174     /*
175      * hibernate delete object
176      */

177     public static void delete(String JavaDoc sql) {
178         Session session = getSession();
179
180         try {
181             session.delete(sql);
182         } catch (Exception JavaDoc e) {
183             Logger.error(DotHibernate.class, "---------- DotHibernate: error on delete ---------------", e);
184             handleSessionException();
185             // throw new DotRuntimeException(e.toString());
186
}
187     }
188
189     public static java.util.List JavaDoc find(String JavaDoc x) {
190         Session session = getSession();
191
192         try {
193             return (ArrayList JavaDoc) session.find(x);
194         } catch (Exception JavaDoc e) {
195             Logger.error(DotHibernate.class, "---------- DotHibernate: error on find ---------------", e);
196             handleSessionException();
197             return new java.util.ArrayList JavaDoc();
198         }
199     }
200
201     public static Object JavaDoc load(Class JavaDoc c, Serializable JavaDoc key) {
202         Session session = getSession();
203
204         try {
205             return (Object JavaDoc) session.load(c, key);
206         } catch (Exception JavaDoc e) {
207             Logger.error(DotHibernate.class, "---------- DotHibernate: error on load ---------------", e);
208             handleSessionException();
209             try {
210                 return c.newInstance();
211             } catch (Exception JavaDoc e1) {
212                 Logger.error(DotHibernate.class, "---------- DotHibernate: error on load ---------------", e1);
213                 return null;
214             }
215         }
216     }
217
218     /*
219      * hibernate RecipientList object
220      */

221     public List JavaDoc list() {
222         getSession();
223         try {
224             if (maxResults > 0) {
225                 query.setMaxResults(maxResults);
226             }
227             if (firstResult > 0) {
228                 query.setFirstResult(firstResult);
229             }
230
231             return (java.util.ArrayList JavaDoc) query.list();
232         } catch (Exception JavaDoc e) {
233             Logger.error(this, "---------- DotHibernate: error on list ---------------", e);
234             handleSessionException();
235             // throw new DotRuntimeException(e.toString());
236
return new java.util.ArrayList JavaDoc();
237         }
238     }
239
240     public Object JavaDoc load(long id) {
241         Session session = getSession();
242
243         if (id == 0) {
244             try {
245                 return thisClass.newInstance();
246             } catch (Exception JavaDoc e) {
247                 throw new DotRuntimeException(e.toString());
248             }
249         }
250
251         try {
252             return session.load(thisClass, new Long JavaDoc(id));
253         } catch (Exception JavaDoc e) {
254             Logger.error(this, "---------- DotHibernate: error on load ---------------", e);
255             handleSessionException();
256
257             // if no object is found in db, return an new Object
258
try {
259                 return thisClass.newInstance();
260             } catch (Exception JavaDoc ex) {
261                 throw new DotRuntimeException(e.toString());
262             }
263         }
264         // return new Object();
265
}
266
267     public Object JavaDoc load(String JavaDoc id) {
268         Session session = getSession();
269
270         if (id == null) {
271             try {
272                 return thisClass.newInstance();
273             } catch (Exception JavaDoc e) {
274                 throw new DotRuntimeException(e.toString());
275             }
276         }
277
278         try {
279             return session.load(thisClass, id);
280         } catch (Exception JavaDoc e) {
281             Logger.error(this, "---------- DotHibernate: error on load ---------------", e);
282             handleSessionException();
283
284             // if no object is found in db, return an new Object
285
try {
286                 return thisClass.newInstance();
287             } catch (Exception JavaDoc ex) {
288                 throw new DotRuntimeException(e.toString());
289             }
290         }
291
292         // return new Object();
293
}
294
295     public Object JavaDoc load() {
296         getSession();
297         ArrayList JavaDoc l = new java.util.ArrayList JavaDoc();
298         Object JavaDoc obj = new Object JavaDoc();
299
300         try {
301             if (maxResults > 0) {
302                 query.setMaxResults(maxResults);
303             }
304
305             l = (java.util.ArrayList JavaDoc) query.list();
306             obj = l.get(0);
307             query = null;
308         } catch (java.lang.IndexOutOfBoundsException JavaDoc iob) {
309             // if no object is found in db, return an new Object
310
try {
311                 obj = thisClass.newInstance();
312             } catch (Exception JavaDoc ex) {
313                 Logger.error(this, query.getQueryString(), ex);
314                 throw new DotRuntimeException(ex.toString());
315             }
316         } catch (Exception JavaDoc e) {
317             Logger.error(this, "---------- DotHibernate: can't load- no results from query---------------", e);
318             handleSessionException();
319
320             try {
321                 obj = thisClass.newInstance();
322             } catch (Exception JavaDoc ee) {
323                 Logger.error(this, "---------- DotHibernate: can't load- thisClass.newInstance()---------------", e);
324                 throw new DotRuntimeException(e.toString());
325             }
326         }
327
328         return obj;
329     }
330
331     public String JavaDoc getQuery() {
332
333         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(this.query.getQueryString() + "\n");
334         try {
335             for (int i = 0; i < this.query.getNamedParameters().length; i++) {
336                 sb.append("param " + i + " = " + query.getNamedParameters()[i]);
337             }
338         } catch (Exception JavaDoc e) {
339         }
340
341         return sb.toString();
342
343     }
344
345     public static void save(Object JavaDoc obj) {
346         Session session = getSession();
347
348         try {
349             session.save(obj);
350             session.flush();
351             // session.save(obj);
352
} catch (Exception JavaDoc e) {
353             Logger.error(DotHibernate.class, "---------- DotHibernate: error on save ---------------", e);
354             handleSessionException();
355             // throw new DotRuntimeException(e.toString());
356
}
357     }
358
359     public static void saveOrUpdate(Object JavaDoc obj) {
360         Session session = getSession();
361         try {
362             session.saveOrUpdate(obj);
363             session.flush();
364             // session.save(obj);
365
} catch (Exception JavaDoc e) {
366             Logger.error(DotHibernate.class, "---------- DotHibernate: error on update ---------------", e);
367             handleSessionException();
368             // throw new DotRuntimeException(e.toString());
369
}
370     }
371
372     public static void update(Object JavaDoc obj) {
373         Session session = getSession();
374
375         try {
376             session.update(obj);
377
378             // session.save(obj);
379
} catch (Exception JavaDoc e) {
380             Logger.error(DotHibernate.class, "---------- DotHibernate: error on update ---------------", e);
381             handleSessionException();
382             // throw new DotRuntimeException(e.toString());
383
}
384     }
385
386     // Session management methods
387

388     private static void buildSessionFactory() {
389         try {
390             // Initialize the Hibernate environment
391
/*
392             ################################
393             ##
394             ## USE THE FILE hibernate.cfg.xml to point to mapping files
395             ##
396             #################################
397             */

398             Configuration cfg = new Configuration().configure();
399             
400             String JavaDoc _dbType = DbConnectionFactory.getDBType();
401             if(_dbType == null){
402                 throw new Exception JavaDoc("DbConnectionFactory.getDBType() is null. Cannot build Hibernate DB Connection without a dbType.");
403             }
404             if (DbConnectionFactory.MYSQL.equals(_dbType)) {
405                 cfg.setProperty("hibernate.dialect", "net.sf.hibernate.dialect.MySQLDialect");
406             } else if (DbConnectionFactory.POSTGRESQL.equals(_dbType)) {
407                 cfg.setProperty("hibernate.dialect", "net.sf.hibernate.dialect.PostgreSQLDialect");
408             } else if (DbConnectionFactory.MSSQL.equals(_dbType)) {
409                 cfg.setProperty("hibernate.dialect", "net.sf.hibernate.dialect.SQLServerDialect");
410             } else if (DbConnectionFactory.ORACLE.equals(_dbType)) {
411                 cfg.setProperty("hibernate.dialect", "net.sf.hibernate.dialect.OracleDialect");
412             }
413             
414             
415             
416             
417             mappings = cfg.createMappings();
418             sessionFactory = cfg.buildSessionFactory();
419             dialect = cfg.getProperty("hibernate.dialect");
420             
421         } catch (Exception JavaDoc e) {
422             Logger
423                     .error(DotHibernate.class, "---------- DotHibernate: error on buildSessionFactory ---------------",
424                             e);
425             // throw new DotRuntimeException(e.toString());
426
}
427     }
428
429     /*
430      * Attempts to find a session associated with the Thread. If there isn't a
431      * session, it will create one.
432      */

433     public static Session getSession() {
434         if (sessionFactory == null) {
435             buildSessionFactory();
436         }
437
438         Session session = (Session) sessionHolder.get();
439
440         if (session == null) {
441             try {
442                 session = sessionFactory.openSession(DbConnectionFactory.getConnection());
443                 sessionHolder.set(session);
444             } catch (Exception JavaDoc e) {
445                 Logger.error(DotHibernate.class, "---------- DotHibernate: error on openSession ---------------", e);
446                 // throw new DotRuntimeException(e.toString());
447
}
448         } else {
449             try {
450                 if (session.connection().isClosed()) {
451                     session.close();
452                     session = sessionFactory.openSession(DbConnectionFactory.getConnection());
453                     sessionHolder.set(session);
454                 }
455             } catch (Exception JavaDoc e) {
456                 Logger.error(DotHibernate.class, "---------- DotHibernate: error on openSession ---------------", e);
457                 // throw new DotRuntimeException(e.toString());
458
}
459         }
460
461         return session;
462     }
463
464     public static void closeSession() {
465         // if there is nothing to close
466
if (sessionHolder.get() == null)
467             return;
468         Session session = getSession();
469
470         if (session != null) {
471             try {
472                 session.flush();
473                 if (!session.connection().getAutoCommit()) {
474                     Logger.debug(DotHibernate.class, "Closing session. Commiting changes!");
475                     session.connection().commit();
476                     session.connection().setAutoCommit(true);
477                 }
478                 DbConnectionFactory.closeConnection();
479                 session.close();
480                 session = null;
481                 sessionHolder.set(null);
482             } catch (Exception JavaDoc ex) {
483                 Logger.error(DotHibernate.class, "---------- DotHibernate: error on closeSession ---------------", ex);
484                 handleSessionException();
485                 // throw new DotRuntimeException(ex.toString());
486
}
487
488         }
489     }
490
491     public static void startTransaction() {
492
493         /*
494          * Transactions are now used by default
495          *
496          */

497         try {
498             getSession().connection().setAutoCommit(false);
499             Logger.debug(DotHibernate.class, "Starting Transaction!");
500         } catch (Exception JavaDoc e) {
501             Logger.error(DotHibernate.class, "---------- DotHibernate: error on startTransaction ---------------", e);
502             handleSessionException();
503             // throw new DotRuntimeException(e.toString());
504
}
505     }
506
507     public static boolean commitTransaction() {
508         closeSession();
509         return true;
510     }
511
512     public static void rollbackTransaction() {
513
514         handleSessionException();
515
516     }
517
518     public static void flush() {
519         Session session = getSession();
520
521         try {
522             session.flush();
523         } catch (Exception JavaDoc e) {
524             Logger.error(DotHibernate.class, "---------- DotHibernate: error on flush ---------------", e);
525             handleSessionException();
526             // throw new DotRuntimeException(e.toString());
527
}
528     }
529
530     private static void handleSessionException() {
531
532         Logger.debug(DotHibernate.class, "handleSessionException");
533         Session session = getSession();
534         session.clear();
535
536         try {
537             session.connection().rollback();
538             session.connection().setAutoCommit(true);
539         } catch (Exception JavaDoc ex) {
540             Logger.error(DotHibernate.class, "---------- DotHibernate: error on rollbackTransaction ---------------",
541                     ex);
542             // throw new DotRuntimeException(ex.toString());
543
}
544
545         try {
546             DbConnectionFactory.closeConnection();
547             session.close();
548             session = null;
549             sessionHolder.set(null);
550         } catch (Exception JavaDoc ex) {
551             Logger.error(DotHibernate.class, "---------- DotHibernate: error on rollbackTransaction ---------------",
552                     ex);
553             // throw new DotRuntimeException(ex.toString());
554
}
555
556     }
557     
558     public static void saveWithPrimaryKey(Object JavaDoc obj, Serializable JavaDoc id) {
559         Session session = getSession();
560
561         try {
562             session.save(obj, id);
563             session.flush();
564             // session.save(obj);
565
} catch (Exception JavaDoc e) {
566             Logger.error(DotHibernate.class, "---------- DotHibernate: error on save ---------------", e);
567             handleSessionException();
568             // throw new DotRuntimeException(e.toString());
569
}
570     }
571     
572     public void setDate(java.util.Date JavaDoc g) {
573         query.setDate(t, g);
574         t++;
575     }
576     
577     
578
579 }
Popular Tags