KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > riot > hibernate > support > HibernateUtils


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.support;
25
26 import java.io.Serializable JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Iterator 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.Criteria;
34 import org.hibernate.EntityMode;
35 import org.hibernate.Hibernate;
36 import org.hibernate.Query;
37 import org.hibernate.Session;
38 import org.hibernate.SessionFactory;
39 import org.hibernate.criterion.Expression;
40 import org.hibernate.metadata.ClassMetadata;
41 import org.riotfamily.common.beans.PropertyUtils;
42 import org.riotfamily.riot.security.AccessController;
43 import org.springframework.util.StringUtils;
44
45 public final class HibernateUtils {
46
47     public static final String JavaDoc LIVE_MODE_FILTER_NAME = "liveMode";
48     
49     public static final String JavaDoc PUBLISHED_PARAM_NAME = "published";
50     
51     private static Log log = LogFactory.getLog(HibernateUtils.class);
52     
53     private HibernateUtils() {
54     }
55
56     public static Object JavaDoc get(Session session, Class JavaDoc beanClass, String JavaDoc id) {
57         SessionFactory sf = session.getSessionFactory();
58         Serializable JavaDoc serialId = convertId(beanClass, id, sf);
59         return session.get(beanClass, serialId);
60     }
61
62     public static Serializable JavaDoc convertId(Class JavaDoc beanClass, String JavaDoc id,
63             SessionFactory sessionFactory) {
64
65         Class JavaDoc identifierClass = sessionFactory.getClassMetadata(beanClass)
66                 .getIdentifierType().getReturnedClass();
67
68         return (Serializable JavaDoc) PropertyUtils.convert(id, identifierClass);
69     }
70
71     public static String JavaDoc getIdAsString(SessionFactory sessionFactory, Object JavaDoc bean) {
72         Class JavaDoc clazz = Hibernate.getClass(bean);
73         ClassMetadata metadata = sessionFactory.getClassMetadata(clazz);
74         return metadata.getIdentifier(bean, EntityMode.POJO).toString();
75     }
76
77     /**
78      * Returns a HQL term that can be used within a where-clause to perform
79      * a query-by-example.
80      * @since 6.4
81      */

82     public static String JavaDoc getExampleWhereClause(Object JavaDoc example, String JavaDoc alias,
83             String JavaDoc[] propertyNames) {
84
85         if (example == null || propertyNames == null) {
86             return null;
87         }
88         StringBuffer JavaDoc hql = new StringBuffer JavaDoc();
89         Map JavaDoc properties;
90         if (example instanceof Map JavaDoc) {
91             properties = (Map JavaDoc) example;
92         }
93         else {
94             properties = PropertyUtils.getProperties(example, propertyNames);
95         }
96         for (int i = 0; i < propertyNames.length; i++) {
97             String JavaDoc name = propertyNames[i];
98             Object JavaDoc value = properties.get(name);
99             if (value != null) {
100                 if (hql.length() > 0) {
101                     hql.append(" and ");
102                 }
103                 if (value instanceof Collection JavaDoc) {
104                     Collection JavaDoc c = (Collection JavaDoc) value;
105                     hql.append("1 = 1");
106                     for (int j = 0; j < c.size(); j++) {
107                         hql.append(" and :").append(name).append("_").append(j)
108                                 .append(" in elements(").append(alias)
109                                 .append('.').append(name).append(')');
110                     }
111                 }
112                 else {
113                     hql.append(alias).append('.').append(name);
114                     hql.append(" = :").append(name);
115                 }
116             }
117         }
118         return hql.length() > 0 ? hql.toString() : null;
119     }
120
121     /**
122      * Sets collection values as individual query parameters. Use this method
123      * together with {@link #getExampleWhereClause(Object, String, String[])}
124      * when your example contains collections.
125      * <p>
126      * The method iterates over the provides names array and inspects the given
127      * bean (or map). If there's a property (or map entry) of the type
128      * <code>java.util.Collection</code>, the methods iterates over the
129      * collection and sets a query parameter for each item. The name is suffixed
130      * with an underscore and the item's index.
131      *
132      * @since 6.4
133      */

134     public static void setCollectionValueParams(Query query,
135             String JavaDoc[] names, Object JavaDoc object) {
136
137         for (int i = 0; i < names.length; i++) {
138             String JavaDoc name = names[i];
139             Object JavaDoc value;
140             if (object instanceof Map JavaDoc) {
141                 value = ((Map JavaDoc) object).get(name);
142             }
143             else {
144                 value = PropertyUtils.getProperty(object, name);
145             }
146             if (value instanceof Collection JavaDoc) {
147                 int j = 0;
148                 Iterator JavaDoc values = ((Collection JavaDoc) value).iterator();
149                 while (values.hasNext()) {
150                     query.setParameter(name + "_" + j++, values.next());
151                 }
152             }
153         }
154     }
155
156     /**
157      * Returns a HQL term that can be used within a where-clause to perform
158      * a search. Example: <code>"(lower(&lt;alias&gt;.&lt;property[0]&gt;)
159      * like :&lt;searchParamName&gt; or lower(&lt;alias&gt;.&lt;property[1]&gt;)
160      * like :&lt;searchParamName&gt; or ...)"</code>
161      * @since 6.4
162      */

163     public static String JavaDoc getSearchWhereClause(String JavaDoc alias,
164             String JavaDoc[] propertyNames, String JavaDoc searchParamName) {
165
166         if (propertyNames == null || propertyNames.length == 0) {
167             return null;
168         }
169         StringBuffer JavaDoc hql = new StringBuffer JavaDoc("(");
170         for (int i = 0; i < propertyNames.length; i++) {
171             String JavaDoc name = propertyNames[i];
172             if (i > 0) {
173                 hql.append(" or ");
174             }
175             hql.append("lower(").append(alias).append('.').append(name);
176             hql.append(") like :").append(searchParamName);
177         }
178         hql.append(')');
179         return hql.toString();
180     }
181
182     /**
183      * Appends the given term to the StringBuffer. If the buffer is not empty,
184      * the provided expression is inserted right before the term (surrounded
185      * by spaces).
186      * @since 6.4
187      */

188     public static StringBuffer JavaDoc appendHql(StringBuffer JavaDoc hql,
189             String JavaDoc expression, String JavaDoc term) {
190
191         if (StringUtils.hasText(term)) {
192             if (expression != null && hql.length() > 0) {
193                 hql.append(' ').append(expression).append(' ');
194             }
195             hql.append(term);
196         }
197         return hql;
198     }
199
200     public static void addEqOrNull(Criteria c, String JavaDoc name, Object JavaDoc val) {
201         if (val != null) {
202             c.add(Expression.eq(name, val));
203         }
204         else {
205             c.add(Expression.isNull(name));
206         }
207     }
208
209     public static boolean isLiveModeFilterDefined(SessionFactory sf) {
210         return sf.getDefinedFilterNames().contains(LIVE_MODE_FILTER_NAME);
211     }
212     
213     public static void enableLiveModeFilterIfNecessary(Session session) {
214         if (!AccessController.isAuthenticatedUser()) {
215             if (isLiveModeFilterDefined(session.getSessionFactory())) {
216                 session.enableFilter(LIVE_MODE_FILTER_NAME).setParameter(
217                         PUBLISHED_PARAM_NAME, Boolean.TRUE);
218             }
219             else {
220                 log.warn("No filter named " + LIVE_MODE_FILTER_NAME
221                         + " defined for SessionFactory");
222             }
223         }
224     }
225 }
226
Popular Tags