View Javadoc

1   /*
2    * Copyright 2000-2004 The Apache Software Foundation.
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.marevol.utils.hibernate;
17  
18  import java.io.Serializable;
19  import java.sql.Connection;
20  import java.util.Enumeration;
21  import java.util.HashMap;
22  import java.util.Iterator;
23  import java.util.Map;
24  
25  import javax.portlet.PortletConfig;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.hibernate.CacheMode;
30  import org.hibernate.Criteria;
31  import org.hibernate.EntityMode;
32  import org.hibernate.Filter;
33  import org.hibernate.FlushMode;
34  import org.hibernate.HibernateException;
35  import org.hibernate.LockMode;
36  import org.hibernate.Query;
37  import org.hibernate.ReplicationMode;
38  import org.hibernate.SQLQuery;
39  import org.hibernate.Session;
40  import org.hibernate.SessionFactory;
41  import org.hibernate.Transaction;
42  import org.hibernate.cfg.Configuration;
43  import org.hibernate.stat.SessionStatistics;
44  
45  /***
46   *  Hibernate Utility
47   * 
48   * @author <a href="mailto:shinsuke@yahoo.co.jp">Shinsuke Sugaya</a>
49   *
50   */
51  public class HibernateUtil
52  {
53      private static Log log = LogFactory.getLog(HibernateUtil.class);
54  
55      public static final String WEBAPP_ROOT = "//$//{webappRoot//}";
56  
57      private static SessionFactory sessionFactory = null;
58  
59      public static final ThreadLocal session = new ThreadLocal();
60  
61      public static final ThreadLocal transaction = new ThreadLocal();
62  
63      public static void init()
64      {
65          try
66          {
67              // Create the SessionFactory
68              sessionFactory = new Configuration().configure().buildSessionFactory();
69          }
70          catch (Throwable ex)
71          {
72              // Make sure you log the exception, as it might be swallowed
73              log.error("Initial SessionFactory creation failed.", ex);
74              throw new ExceptionInInitializerError(ex);
75          }
76      }
77  
78      public static void init(PortletConfig portletConfig)
79      {
80          String webappRoot = portletConfig.getPortletContext().getRealPath("/");
81          if (log.isDebugEnabled())
82          {
83              log.debug("init(PortletConfig) -  : webappRoot=" + webappRoot);
84          }
85  
86          // To avoid StringIndexOutOfBoundsException.. \ -> ////
87          webappRoot = webappRoot.replaceAll("////", "////////////////");
88  
89          HashMap map = new HashMap();
90          map.put(WEBAPP_ROOT, webappRoot);
91          init(map);
92      }
93  
94      public static void init(Map map)
95      {
96  
97          Configuration config = new Configuration().configure();
98          for (Enumeration e = config.getProperties().keys(); e.hasMoreElements();)
99          {
100             String key = (String) e.nextElement();
101             String value = config.getProperty(key);
102             if (log.isDebugEnabled())
103             {
104                 log.debug("init(Map) -  : key=" + key + ", value=" + value);
105             }
106 
107             Iterator ite = map.keySet().iterator();
108             while (ite.hasNext())
109             {
110                 String keyword = (String) ite.next();
111                 if (value.matches(".*" + keyword + ".*"))
112                 {
113                     if (log.isDebugEnabled())
114                     {
115                         log.debug("init(Map) -  : key=" + key + ", value=" + value+", keyword="+keyword+", val="+ map.get(keyword));
116                     }
117                     value = value.replaceAll(keyword, (String) map.get(keyword));
118                     config.setProperty(key, value);
119                     if (log.isDebugEnabled())
120                     {
121                         log.debug("init(Map) -  : REPLACED: key=" + key + ", value=" + value);
122                     }
123                 }
124             }
125 
126             // for HSQL
127             if (key.equals("hibernate.connection.url") && value.startsWith("jdbc:hsqldb:"))
128             {
129                 value = value.replace('//', '/');
130                 config.setProperty(key, value);
131                 if (log.isDebugEnabled())
132                 {
133                     log.debug("init(Map) -  : REPLACED: key=" + key + ", value=" + value);
134                 }
135             }
136         }
137 
138         try
139         {
140             // Create the SessionFactory
141             sessionFactory = config.buildSessionFactory();
142         }
143         catch (Throwable ex)
144         {
145             // Make sure you log the exception, as it might be swallowed
146             log.error("Initial SessionFactory creation failed.", ex);
147             throw new ExceptionInInitializerError(ex);
148         }
149     }
150 
151     private static SessionFactory getSessionFactoryInstance()
152     {
153         if (sessionFactory == null)
154         {
155             init();
156         }
157         return sessionFactory;
158     }
159 
160     public static void openSession()
161     {
162         getCurrentSession();
163     }
164 
165     public static Session getCurrentSession()
166     {
167         Session s = (Session) session.get();
168         // Open a new Session, if this Thread has none yet
169         if (s == null)
170         {
171             s = getSessionFactoryInstance().openSession();
172             session.set(s);
173         }
174         return s;
175     }
176 
177     public static void closeSession()
178     {
179         Session s = (Session) session.get();
180         if (s != null)
181         {
182             s.close();
183         }
184         session.set(null);
185     }
186 
187     public static Transaction beginTransaction()
188     {
189 
190         Transaction tx = (Transaction) transaction.get();
191         if (tx == null)
192         {
193             tx = getCurrentSession().beginTransaction();
194             transaction.set(tx);
195         }
196         return tx;
197     }
198 
199     public static void commit()
200     {
201         Transaction tx = (Transaction) transaction.get();
202         if (tx != null)
203         {
204             tx.commit();
205         }
206         transaction.set(null);
207     }
208 
209     public static void rollback()
210     {
211         Transaction tx = (Transaction) transaction.get();
212         if (tx != null)
213         {
214             tx.rollback();
215         }
216         transaction.set(null);
217     }
218 
219     public static Serializable save(Object arg0)
220     {
221         return getCurrentSession().save(arg0);
222     }
223 
224     public static Object load(Class arg0, Serializable arg1)
225     {
226         return getCurrentSession().load(arg0, arg1);
227     }
228 
229     /* (non-Javadoc)
230      * @see org.hibernate.Session#cancelQuery()
231      */
232     public static void cancelQuery() throws HibernateException
233     {
234         getCurrentSession().cancelQuery();
235     }
236 
237     /* (non-Javadoc)
238      * @see org.hibernate.Session#clear()
239      */
240     public static void clear()
241     {
242         getCurrentSession().clear();
243     }
244 
245     /* (non-Javadoc)
246      * @see org.hibernate.Session#close()
247      */
248     public static Connection close() throws HibernateException
249     {
250         return getCurrentSession().close();
251     }
252 
253     /* (non-Javadoc)
254      * @see org.hibernate.Session#connection()
255      */
256     public static Connection connection() throws HibernateException
257     {
258         return getCurrentSession().connection();
259     }
260 
261     /* (non-Javadoc)
262      * @see org.hibernate.Session#contains(java.lang.Object)
263      */
264     public static boolean contains(Object arg0)
265     {
266         return getCurrentSession().contains(arg0);
267     }
268 
269     /* (non-Javadoc)
270      * @see org.hibernate.Session#createCriteria(java.lang.Class, java.lang.String)
271      */
272     public static Criteria createCriteria(Class arg0, String arg1)
273     {
274         return getCurrentSession().createCriteria(arg0, arg1);
275     }
276 
277     /* (non-Javadoc)
278      * @see org.hibernate.Session#createCriteria(java.lang.Class)
279      */
280     public static Criteria createCriteria(Class arg0)
281     {
282         return getCurrentSession().createCriteria(arg0);
283     }
284 
285     /* (non-Javadoc)
286      * @see org.hibernate.Session#createCriteria(java.lang.String, java.lang.String)
287      */
288     public static Criteria createCriteria(String arg0, String arg1)
289     {
290         return getCurrentSession().createCriteria(arg0, arg1);
291     }
292 
293     /* (non-Javadoc)
294      * @see org.hibernate.Session#createCriteria(java.lang.String)
295      */
296     public static Criteria createCriteria(String arg0)
297     {
298         return getCurrentSession().createCriteria(arg0);
299     }
300 
301     /* (non-Javadoc)
302      * @see org.hibernate.Session#createFilter(java.lang.Object, java.lang.String)
303      */
304     public static Query createFilter(Object arg0, String arg1) throws HibernateException
305     {
306         return getCurrentSession().createFilter(arg0, arg1);
307     }
308 
309     /* (non-Javadoc)
310      * @see org.hibernate.Session#createQuery(java.lang.String)
311      */
312     public static Query createQuery(String arg0) throws HibernateException
313     {
314         return getCurrentSession().createQuery(arg0);
315     }
316 
317     /* (non-Javadoc)
318      * @see org.hibernate.Session#createSQLQuery(java.lang.String)
319      */
320     public static SQLQuery createSQLQuery(String arg0) throws HibernateException
321     {
322         return getCurrentSession().createSQLQuery(arg0);
323     }
324 
325     /* (non-Javadoc)
326      * @see org.hibernate.Session#delete(java.lang.Object)
327      */
328     public static void delete(Object arg0) throws HibernateException
329     {
330         getCurrentSession().delete(arg0);
331     }
332 
333     /* (non-Javadoc)
334      * @see org.hibernate.Session#disableFilter(java.lang.String)
335      */
336     public static void disableFilter(String arg0)
337     {
338         getCurrentSession().disableFilter(arg0);
339     }
340 
341     /* (non-Javadoc)
342      * @see org.hibernate.Session#disconnect()
343      */
344     public static Connection disconnect() throws HibernateException
345     {
346         return getCurrentSession().disconnect();
347     }
348 
349     /* (non-Javadoc)
350      * @see org.hibernate.Session#enableFilter(java.lang.String)
351      */
352     public static Filter enableFilter(String arg0)
353     {
354         return getCurrentSession().enableFilter(arg0);
355     }
356 
357     /* (non-Javadoc)
358      * @see org.hibernate.Session#evict(java.lang.Object)
359      */
360     public static void evict(Object arg0) throws HibernateException
361     {
362         getCurrentSession().evict(arg0);
363     }
364 
365     /* (non-Javadoc)
366      * @see org.hibernate.Session#flush()
367      */
368     public static void flush() throws HibernateException
369     {
370         getCurrentSession().flush();
371     }
372 
373     /* (non-Javadoc)
374      * @see org.hibernate.Session#get(java.lang.Class, java.io.Serializable, org.hibernate.LockMode)
375      */
376     public static Object get(Class arg0, Serializable arg1, LockMode arg2) throws HibernateException
377     {
378         return getCurrentSession().get(arg0, arg1, arg2);
379     }
380 
381     /* (non-Javadoc)
382      * @see org.hibernate.Session#get(java.lang.Class, java.io.Serializable)
383      */
384     public static Object get(Class arg0, Serializable arg1) throws HibernateException
385     {
386         return getCurrentSession().get(arg0, arg1);
387     }
388 
389     /* (non-Javadoc)
390      * @see org.hibernate.Session#get(java.lang.String, java.io.Serializable, org.hibernate.LockMode)
391      */
392     public static Object get(String arg0, Serializable arg1, LockMode arg2) throws HibernateException
393     {
394         return getCurrentSession().get(arg0, arg1, arg2);
395     }
396 
397     /* (non-Javadoc)
398      * @see org.hibernate.Session#get(java.lang.String, java.io.Serializable)
399      */
400     public static Object get(String arg0, Serializable arg1) throws HibernateException
401     {
402         return getCurrentSession().get(arg0, arg1);
403     }
404 
405     /* (non-Javadoc)
406      * @see org.hibernate.Session#getCacheMode()
407      */
408     public static CacheMode getCacheMode()
409     {
410         return getCurrentSession().getCacheMode();
411     }
412 
413     /* (non-Javadoc)
414      * @see org.hibernate.Session#getCurrentLockMode(java.lang.Object)
415      */
416     public static LockMode getCurrentLockMode(Object arg0) throws HibernateException
417     {
418         return getCurrentSession().getCurrentLockMode(arg0);
419     }
420 
421     /* (non-Javadoc)
422      * @see org.hibernate.Session#getEnabledFilter(java.lang.String)
423      */
424     public static Filter getEnabledFilter(String arg0)
425     {
426         return getCurrentSession().getEnabledFilter(arg0);
427     }
428 
429     /* (non-Javadoc)
430      * @see org.hibernate.Session#getEntityMode()
431      */
432     public static EntityMode getEntityMode()
433     {
434         return getCurrentSession().getEntityMode();
435     }
436 
437     /* (non-Javadoc)
438      * @see org.hibernate.Session#getEntityName(java.lang.Object)
439      */
440     public static String getEntityName(Object arg0) throws HibernateException
441     {
442         return getCurrentSession().getEntityName(arg0);
443     }
444 
445     /* (non-Javadoc)
446      * @see org.hibernate.Session#getFlushMode()
447      */
448     public static FlushMode getFlushMode()
449     {
450         return getCurrentSession().getFlushMode();
451     }
452 
453     /* (non-Javadoc)
454      * @see org.hibernate.Session#getIdentifier(java.lang.Object)
455      */
456     public static Serializable getIdentifier(Object arg0) throws HibernateException
457     {
458         return getCurrentSession().getIdentifier(arg0);
459     }
460 
461     /* (non-Javadoc)
462      * @see org.hibernate.Session#getNamedQuery(java.lang.String)
463      */
464     public static Query getNamedQuery(String arg0) throws HibernateException
465     {
466         return getCurrentSession().getNamedQuery(arg0);
467     }
468 
469     /* (non-Javadoc)
470      * @see org.hibernate.Session#getSession(org.hibernate.EntityMode)
471      */
472     public static Session getSession(EntityMode arg0)
473     {
474         return getCurrentSession().getSession(arg0);
475     }
476 
477     /* (non-Javadoc)
478      * @see org.hibernate.Session#getSessionFactory()
479      */
480     public static SessionFactory getSessionFactory()
481     {
482         return getCurrentSession().getSessionFactory();
483     }
484 
485     /* (non-Javadoc)
486      * @see org.hibernate.Session#getStatistics()
487      */
488     public static SessionStatistics getStatistics()
489     {
490         return getCurrentSession().getStatistics();
491     }
492 
493     /* (non-Javadoc)
494      * @see org.hibernate.Session#isConnected()
495      */
496     public static boolean isConnected()
497     {
498         return getCurrentSession().isConnected();
499     }
500 
501     /* (non-Javadoc)
502      * @see org.hibernate.Session#isDirty()
503      */
504     public static boolean isDirty() throws HibernateException
505     {
506         return getCurrentSession().isDirty();
507     }
508 
509     /* (non-Javadoc)
510      * @see org.hibernate.Session#isOpen()
511      */
512     public static boolean isOpen()
513     {
514         return getCurrentSession().isOpen();
515     }
516 
517     /* (non-Javadoc)
518      * @see org.hibernate.Session#load(java.lang.Class, java.io.Serializable, org.hibernate.LockMode)
519      */
520     public static Object load(Class arg0, Serializable arg1, LockMode arg2) throws HibernateException
521     {
522         return getCurrentSession().load(arg0, arg1, arg2);
523     }
524 
525     /* (non-Javadoc)
526      * @see org.hibernate.Session#load(java.lang.Object, java.io.Serializable)
527      */
528     public static void load(Object arg0, Serializable arg1) throws HibernateException
529     {
530         getCurrentSession().load(arg0, arg1);
531     }
532 
533     /* (non-Javadoc)
534      * @see org.hibernate.Session#load(java.lang.String, java.io.Serializable, org.hibernate.LockMode)
535      */
536     public static Object load(String arg0, Serializable arg1, LockMode arg2) throws HibernateException
537     {
538         return getCurrentSession().load(arg0, arg1, arg2);
539     }
540 
541     /* (non-Javadoc)
542      * @see org.hibernate.Session#load(java.lang.String, java.io.Serializable)
543      */
544     public static Object load(String arg0, Serializable arg1) throws HibernateException
545     {
546         return getCurrentSession().load(arg0, arg1);
547     }
548 
549     /* (non-Javadoc)
550      * @see org.hibernate.Session#lock(java.lang.Object, org.hibernate.LockMode)
551      */
552     public static void lock(Object arg0, LockMode arg1) throws HibernateException
553     {
554         getCurrentSession().lock(arg0, arg1);
555     }
556 
557     /* (non-Javadoc)
558      * @see org.hibernate.Session#lock(java.lang.String, java.lang.Object, org.hibernate.LockMode)
559      */
560     public static void lock(String arg0, Object arg1, LockMode arg2) throws HibernateException
561     {
562         getCurrentSession().lock(arg0, arg1, arg2);
563     }
564 
565     /* (non-Javadoc)
566      * @see org.hibernate.Session#merge(java.lang.Object)
567      */
568     public static Object merge(Object arg0) throws HibernateException
569     {
570         return getCurrentSession().merge(arg0);
571     }
572 
573     /* (non-Javadoc)
574      * @see org.hibernate.Session#merge(java.lang.String, java.lang.Object)
575      */
576     public static Object merge(String arg0, Object arg1) throws HibernateException
577     {
578         return getCurrentSession().merge(arg0, arg1);
579     }
580 
581     /* (non-Javadoc)
582      * @see org.hibernate.Session#persist(java.lang.Object)
583      */
584     public static void persist(Object arg0) throws HibernateException
585     {
586         getCurrentSession().persist(arg0);
587     }
588 
589     /* (non-Javadoc)
590      * @see org.hibernate.Session#persist(java.lang.String, java.lang.Object)
591      */
592     public static void persist(String arg0, Object arg1) throws HibernateException
593     {
594         getCurrentSession().persist(arg0, arg1);
595     }
596 
597     /* (non-Javadoc)
598      * @see org.hibernate.Session#reconnect()
599      */
600     public static void reconnect() throws HibernateException
601     {
602         getCurrentSession().reconnect();
603     }
604 
605     /* (non-Javadoc)
606      * @see org.hibernate.Session#reconnect(java.sql.Connection)
607      */
608     public static void reconnect(Connection arg0) throws HibernateException
609     {
610         getCurrentSession().reconnect(arg0);
611     }
612 
613     /* (non-Javadoc)
614      * @see org.hibernate.Session#refresh(java.lang.Object, org.hibernate.LockMode)
615      */
616     public static void refresh(Object arg0, LockMode arg1) throws HibernateException
617     {
618         getCurrentSession().refresh(arg0, arg1);
619     }
620 
621     /* (non-Javadoc)
622      * @see org.hibernate.Session#refresh(java.lang.Object)
623      */
624     public static void refresh(Object arg0) throws HibernateException
625     {
626         getCurrentSession().refresh(arg0);
627     }
628 
629     /* (non-Javadoc)
630      * @see org.hibernate.Session#replicate(java.lang.Object, org.hibernate.ReplicationMode)
631      */
632     public static void replicate(Object arg0, ReplicationMode arg1) throws HibernateException
633     {
634         getCurrentSession().replicate(arg0, arg1);
635     }
636 
637     /* (non-Javadoc)
638      * @see org.hibernate.Session#replicate(java.lang.String, java.lang.Object, org.hibernate.ReplicationMode)
639      */
640     public static void replicate(String arg0, Object arg1, ReplicationMode arg2) throws HibernateException
641     {
642         getCurrentSession().replicate(arg0, arg1, arg2);
643     }
644 
645     /* (non-Javadoc)
646      * @see org.hibernate.Session#save(java.lang.Object, java.io.Serializable)
647      */
648     public static void save(Object arg0, Serializable arg1) throws HibernateException
649     {
650         getCurrentSession().save(arg0, arg1);
651     }
652 
653     /* (non-Javadoc)
654      * @see org.hibernate.Session#save(java.lang.String, java.lang.Object, java.io.Serializable)
655      */
656     public static void save(String arg0, Object arg1, Serializable arg2) throws HibernateException
657     {
658         getCurrentSession().save(arg0, arg1, arg2);
659     }
660 
661     /* (non-Javadoc)
662      * @see org.hibernate.Session#save(java.lang.String, java.lang.Object)
663      */
664     public static Serializable save(String arg0, Object arg1) throws HibernateException
665     {
666         return getCurrentSession().save(arg0, arg1);
667     }
668 
669     /* (non-Javadoc)
670      * @see org.hibernate.Session#saveOrUpdate(java.lang.Object)
671      */
672     public static void saveOrUpdate(Object arg0) throws HibernateException
673     {
674         getCurrentSession().saveOrUpdate(arg0);
675     }
676 
677     /* (non-Javadoc)
678      * @see org.hibernate.Session#saveOrUpdate(java.lang.String, java.lang.Object)
679      */
680     public static void saveOrUpdate(String arg0, Object arg1) throws HibernateException
681     {
682         getCurrentSession().saveOrUpdate(arg0, arg1);
683     }
684 
685     /* (non-Javadoc)
686      * @see org.hibernate.Session#setCacheMode(org.hibernate.CacheMode)
687      */
688     public static void setCacheMode(CacheMode arg0)
689     {
690         getCurrentSession().setCacheMode(arg0);
691     }
692 
693     /* (non-Javadoc)
694      * @see org.hibernate.Session#setFlushMode(org.hibernate.FlushMode)
695      */
696     public static void setFlushMode(FlushMode arg0)
697     {
698         getCurrentSession().setFlushMode(arg0);
699     }
700 
701     /* (non-Javadoc)
702      * @see org.hibernate.Session#update(java.lang.Object, java.io.Serializable)
703      */
704     public static void update(Object arg0, Serializable arg1) throws HibernateException
705     {
706         getCurrentSession().update(arg0, arg1);
707     }
708 
709     /* (non-Javadoc)
710      * @see org.hibernate.Session#update(java.lang.Object)
711      */
712     public static void update(Object arg0) throws HibernateException
713     {
714         getCurrentSession().update(arg0);
715     }
716 
717     /* (non-Javadoc)
718      * @see org.hibernate.Session#update(java.lang.String, java.lang.Object, java.io.Serializable)
719      */
720     public static void update(String arg0, Object arg1, Serializable arg2) throws HibernateException
721     {
722         getCurrentSession().update(arg0, arg1, arg2);
723     }
724 
725     /* (non-Javadoc)
726      * @see org.hibernate.Session#update(java.lang.String, java.lang.Object)
727      */
728     public static void update(String arg0, Object arg1) throws HibernateException
729     {
730         getCurrentSession().update(arg0, arg1);
731     }
732 
733 }