KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > riot > hibernate > dao > HqlDao


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1
3  * The contents of this file are subject to the Mozilla Public License Version
4  * 1.1 (the "License"); you may not use this file except in compliance with
5  * the License. You may obtain a copy of the License at
6  * http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the
11  * License.
12  *
13  * The Original Code is Riot.
14  *
15  * The Initial Developer of the Original Code is
16  * Neteye GmbH.
17  * Portions created by the Initial Developer are Copyright (C) 2006
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  * Felix Gnass [fgnass at neteye dot de]
22  *
23  * ***** END LICENSE BLOCK ***** */

24 package org.riotfamily.riot.hibernate.dao;
25
26 import java.util.Collection JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.hibernate.Query;
34 import org.riotfamily.common.beans.PropertyUtils;
35 import org.riotfamily.riot.dao.ListParams;
36 import org.riotfamily.riot.dao.Order;
37 import org.riotfamily.riot.dao.RiotDao;
38 import org.riotfamily.riot.dao.SortableDao;
39 import org.riotfamily.riot.dao.SwappableItemDao;
40 import org.riotfamily.riot.hibernate.support.HibernateSupport;
41 import org.riotfamily.riot.hibernate.support.HibernateUtils;
42 import org.springframework.util.Assert;
43
44 /**
45  * RiotDao implementation based on Hibernate.
46  */

47 public class HqlDao extends HibernateSupport implements RiotDao,
48         SortableDao, SwappableItemDao {
49
50     private static final Log log = LogFactory.getLog(HqlDao.class);
51
52     private Class JavaDoc entityClass;
53
54     private boolean polymorph = true;
55
56     private String JavaDoc where;
57
58     private String JavaDoc positionProperty;
59
60     /**
61      * @return Returns the itemClass.
62      */

63     public Class JavaDoc getEntityClass() {
64         return entityClass;
65     }
66
67     /**
68      * @param itemClass The itemClass to set.
69      */

70     public void setEntityClass(Class JavaDoc itemClass) {
71         this.entityClass = itemClass;
72     }
73
74     /**
75      * @return Returns the polymorph.
76      */

77     public boolean isPolymorph() {
78         return polymorph;
79     }
80
81     /**
82      * @param polymorph The polymorph to set.
83      */

84     public void setPolymorph(boolean polymorph) {
85         this.polymorph = polymorph;
86     }
87
88     /**
89      * @return Returns the where.
90      */

91     public String JavaDoc getWhere() {
92         return where;
93     }
94
95     /**
96      * @param where The where to set.
97      */

98     public void setWhere(String JavaDoc where) {
99         this.where = where;
100     }
101
102     /**
103      * @deprecated The objectId is now obtained using Hibernate meta data.
104      */

105     public void setIdProperty(String JavaDoc idProperty) {
106     }
107
108     public void setPositionProperty(String JavaDoc positionProperty) {
109         this.positionProperty = positionProperty;
110     }
111
112     public String JavaDoc getObjectId(Object JavaDoc item) {
113         return HibernateUtils.getIdAsString(getSessionFactory(), item);
114     }
115
116     /**
117      * Returns a list of items.
118      */

119     public Collection JavaDoc list(Object JavaDoc parent, ListParams params) {
120         return listInternal(parent, params);
121     }
122
123     protected List JavaDoc listInternal(Object JavaDoc parent, ListParams params) {
124         Query query = createQuery(buildHql(parent, params));
125         setQueryParameters(query, parent, params);
126         if (params.getPageSize() > 0) {
127             query.setFirstResult(params.getOffset());
128             query.setMaxResults(params.getPageSize());
129         }
130         return query.list();
131     }
132
133     /**
134      * Returns the total number of items.
135      */

136     public int getListSize(Object JavaDoc parent, ListParams params) {
137         Query query = createQuery(buildCountHql(parent, params));
138         setQueryParameters(query, parent, params);
139         Number JavaDoc size = (Number JavaDoc) query.uniqueResult();
140         if (size == null) {
141             return 0;
142         }
143         return size.intValue();
144     }
145
146     protected void setQueryParameters(Query query, Object JavaDoc parent,
147             ListParams params) {
148
149         if (params.getFilter() != null) {
150             if (params.getFilter() instanceof Map JavaDoc) {
151                 Map JavaDoc filterMap = (Map JavaDoc) params.getFilter();
152                 query.setProperties(filterMap);
153             }
154             else {
155                 query.setProperties(params.getFilter());
156             }
157
158             HibernateUtils.setCollectionValueParams(query,
159                     params.getFilteredProperties(), params.getFilter());
160         }
161         if (params.getSearch() != null) {
162             query.setParameter("search", params.getSearch()
163                     .toLowerCase().replace('*', '%') + "%");
164         }
165     }
166
167     /**
168      * Builds a HQL query string to retrieve the total number of items.
169      */

170     protected String JavaDoc buildCountHql(Object JavaDoc parent, ListParams params) {
171         StringBuffer JavaDoc hql = new StringBuffer JavaDoc();
172         hql.append("select count(this) from ");
173         hql.append(entityClass.getName());
174         hql.append(" as this");
175         HibernateUtils.appendHql(hql, "where", getWhereClause(parent, params));
176         log.info(hql);
177         return hql.toString();
178     }
179
180     /**
181      * Builds a HQL query string to retrieve a list of items.
182      */

183     protected String JavaDoc buildHql(Object JavaDoc parent, ListParams params) {
184         StringBuffer JavaDoc hql = new StringBuffer JavaDoc();
185         hql.append("select this from ");
186         hql.append(entityClass.getName());
187         hql.append(" as this");
188         HibernateUtils.appendHql(hql, "where", getWhereClause(parent, params));
189         HibernateUtils.appendHql(hql, "order by", getOrderBy(params));
190         log.info(hql);
191         return hql.toString();
192     }
193
194     protected String JavaDoc getWhereClause(Object JavaDoc parent, ListParams params) {
195         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
196         HibernateUtils.appendHql(sb, null, where);
197
198         if (params.getFilter() != null) {
199             String JavaDoc filter = HibernateUtils.getExampleWhereClause(
200                     params.getFilter(), "this",
201                     params.getFilteredProperties());
202
203             HibernateUtils.appendHql(sb, "and", filter);
204         }
205
206         if (params.getSearch() != null) {
207             String JavaDoc search = HibernateUtils.getSearchWhereClause("this",
208                     params.getSearchProperties(), "search");
209
210             HibernateUtils.appendHql(sb, "and", search);
211         }
212
213         if (!polymorph) {
214             HibernateUtils.appendHql(sb, "and", "(this.class = ")
215                 .append(entityClass.getName()).append(')');
216         }
217
218         return sb.toString();
219     }
220
221     protected String JavaDoc getOrderBy(ListParams params) {
222         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
223         if (params.hasOrder()) {
224             Iterator JavaDoc it = params.getOrder().iterator();
225             while (it.hasNext()) {
226                 Order order = (Order) it.next();
227                 if (!order.isCaseSensitive()) {
228                     sb.append(" lower(");
229                 }
230                 sb.append(" this.");
231                 sb.append(order.getProperty());
232                 if (!order.isCaseSensitive()) {
233                     sb.append(" ) ");
234                 }
235                 sb.append(' ');
236                 sb.append(order.isAscending() ? "asc" : "desc");
237                 if (it.hasNext()) {
238                     sb.append(',');
239                 }
240             }
241         }
242         return sb.toString();
243     }
244
245     public void save(Object JavaDoc entity, Object JavaDoc parent) {
246         getSession().save(entity);
247     }
248
249     public void delete(Object JavaDoc entity, Object JavaDoc parent) {
250         getSession().delete(entity);
251     }
252
253     public Object JavaDoc load(String JavaDoc objectId) {
254         Assert.notNull(objectId, "A non-null id must be passed to load()");
255         return HibernateUtils.get(getSession(), entityClass, objectId);
256     }
257
258     public void update(Object JavaDoc entity) {
259         getSession().update(entity);
260     }
261
262     public void swapEntity(Object JavaDoc item, Object JavaDoc parent, ListParams params,
263             int swapWith) {
264
265         Assert.notNull(positionProperty, "A positionProperty must be specified.");
266
267         List JavaDoc items = listInternal(parent, params);
268         Object JavaDoc nextItem = items.get(swapWith);
269
270         Object JavaDoc pos1 = PropertyUtils.getProperty(item, positionProperty);
271         Object JavaDoc pos2 = PropertyUtils.getProperty(nextItem, positionProperty);
272
273         PropertyUtils.setProperty(item, positionProperty, pos2);
274         PropertyUtils.setProperty(nextItem, positionProperty, pos1);
275
276         getSession().update(item);
277         getSession().update(nextItem);
278     }
279
280 }
Popular Tags