KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > bsf > smartValueObject > mediator > HibernateMediator


1 package org.bsf.smartValueObject.mediator;
2
3 import net.sf.hibernate.*;
4 import net.sf.hibernate.expression.Expression;
5 import net.sf.hibernate.cfg.Configuration;
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8
9 import java.util.Collection JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.Properties JavaDoc;
12 import java.lang.reflect.Field JavaDoc;
13
14 /**
15  * Mediator for Hibernate.
16  *
17  */

18 public class HibernateMediator implements Mediator {
19     private static final Log log = LogFactory.getLog(HibernateMediator.class);
20     private SessionFactory sessions;
21     private static final String JavaDoc USERNAME = "test";
22     private static final String JavaDoc PASSWORD = "test";
23     private static final Object JavaDoc DBNAME = "test";
24     private String JavaDoc indexField = "id";
25     private MediatorConfig config;
26
27     public HibernateMediator(MediatorConfig config) {
28         this.config = config;
29         initHibernate(config.getClasses());
30     }
31
32     private void initHibernate(Collection JavaDoc classes) {
33         try {
34             Configuration config = new Configuration();
35
36             for (Iterator JavaDoc it = classes.iterator(); it.hasNext(); )
37                 config.addClass((Class JavaDoc)it.next());
38
39 // config.setProperties(getMySqlProperties());
40
config.setProperties(getHsqlDbProperties());
41             sessions = config.buildSessionFactory();
42             log.debug("created SessionFactory");
43         } catch (HibernateException e) {
44             log.fatal("could not create SessionFactory", e);
45         }
46     }
47
48     /**
49      * Gets configuration for MySQL.
50      * @return
51      */

52     private Properties JavaDoc getMySqlProperties() {
53         Properties JavaDoc props = new Properties JavaDoc();
54         props.setProperty("hibernate.dialect",
55                 "net.sf.hibernate.dialect.MySQLDialect");
56
57         props.setProperty("hibernate.cache.provider_class",
58                 "net.sf.hibernate.cache.HashtableCacheProvider");
59
60         props.setProperty("hibernate.connection.driver_class",
61                 "com.mysql.jdbc.Driver");
62
63         props.setProperty("hibernate.connection.username", USERNAME);
64         props.setProperty("hibernate.connection.password", PASSWORD);
65         props.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/" + DBNAME);
66         return props;
67     }
68
69     /**
70      * Gets configuration for HsqlDB.
71      * @return
72      */

73     private Properties JavaDoc getHsqlDbProperties() {
74         Properties JavaDoc props = new Properties JavaDoc();
75         props.setProperty("hibernate.dialect",
76                 "net.sf.hibernate.dialect.HSQLDialect");
77
78         props.setProperty("hibernate.cache.provider_class",
79                 "net.sf.hibernate.cache.HashtableCacheProvider");
80
81         props.setProperty("hibernate.connection.driver_class",
82                 "org.hsqldb.jdbcDriver");
83
84         props.setProperty("hibernate.connection.username", "sa");
85         props.setProperty("hibernate.connection.password", "");
86         props.setProperty("hibernate.connection.url", "jdbc:hsqldb:" + DBNAME);
87         return props;
88     }
89
90     /**
91      * Retrieves a graph based on given prototype.
92      *
93      * @param prototype a prototype to obtain a initialized graph.
94      * @return
95      * @throws MediatorException
96      */

97     public Object JavaDoc getGraph(Object JavaDoc prototype)
98             throws MediatorException {
99         try {
100             Object JavaDoc pk = getPK(prototype);
101
102             Session s = sessions.openSession();
103             Criteria crit = s.createCriteria(prototype.getClass());
104             crit.add(Expression.eq(indexField, pk));
105             return crit.uniqueResult();
106         } catch (HibernateException e) {
107             throw new MediatorException(e);
108         }
109     }
110
111     /**
112      * Stores a graph.
113      *
114      * @param graph the root element of the graph.
115      * @throws MediatorException
116      */

117     public ChangeSummary updateGraph(Object JavaDoc graph)
118             throws MediatorException {
119         Session s = null;
120         Transaction tx = null;
121
122         try {
123             s = sessions.openSession();
124             tx = s.beginTransaction();
125             s.saveOrUpdate(graph);
126             tx.commit();
127             s.close();
128         } catch (HibernateException e) {
129             try { if (tx!=null) tx.rollback(); }
130             catch (HibernateException he) {}
131             throw new MediatorException(e);
132         }
133         return new ChangeSummary(getPK(graph), null);
134     }
135
136     /**
137      * Deletes a graph.
138      * @param graph the root element of the graph.
139      * @throws MediatorException
140      */

141     public void deleteGraph(Object JavaDoc graph)
142             throws MediatorException {
143         Transaction tx = null;
144         Session s = null;
145         try {
146             s = sessions.openSession();
147             tx = s.beginTransaction();
148             s.delete(graph);
149             tx.commit();
150             s.close();
151         } catch (HibernateException e) {
152             try { if (tx!=null) tx.rollback(); }
153             catch (HibernateException he) {}
154             throw new MediatorException();
155         }
156     }
157
158     /**
159       * Gets primary key from object (from the field specied in indexField).
160       * @param o
161       * @return
162       * @throws MediatorException
163       */

164      private Object JavaDoc getPK(Object JavaDoc o) throws MediatorException {
165          Object JavaDoc pk;
166          try {
167              Field JavaDoc field = o.getClass().getField(indexField);
168              pk = field.get(o);
169          } catch (Exception JavaDoc e) {
170              throw new MediatorException("Could not find pk", e);
171          }
172          return pk;
173      }
174 }
175
Popular Tags