01: //$Id: InExpression.java 7557 2005-07-19 23:25:36Z oneovthafew $
02: package org.hibernate.criterion;
03:
04: import java.util.ArrayList;
05:
06: import org.hibernate.Criteria;
07: import org.hibernate.EntityMode;
08: import org.hibernate.HibernateException;
09:
10: import org.hibernate.engine.TypedValue;
11:
12: import org.hibernate.type.AbstractComponentType;
13: import org.hibernate.type.Type;
14: import org.hibernate.util.StringHelper;
15:
16: /**
17: * Constrains the property to a specified list of values
18: * @author Gavin King
19: */
20: public class InExpression implements Criterion {
21:
22: private final String propertyName;
23: private final Object[] values;
24:
25: protected InExpression(String propertyName, Object[] values) {
26: this .propertyName = propertyName;
27: this .values = values;
28: }
29:
30: public String toSqlString(Criteria criteria,
31: CriteriaQuery criteriaQuery) throws HibernateException {
32: String[] columns = criteriaQuery.getColumnsUsingProjection(
33: criteria, propertyName);
34: String singleValueParam = StringHelper.repeat("?, ",
35: columns.length - 1)
36: + "?";
37: if (columns.length > 1)
38: singleValueParam = '(' + singleValueParam + ')';
39: String params = values.length > 0 ? StringHelper.repeat(
40: singleValueParam + ", ", values.length - 1)
41: + singleValueParam : "";
42: String cols = StringHelper.join(", ", columns);
43: if (columns.length > 1)
44: cols = '(' + cols + ')';
45: return cols + " in (" + params + ')';
46: }
47:
48: public TypedValue[] getTypedValues(Criteria criteria,
49: CriteriaQuery criteriaQuery) throws HibernateException {
50: ArrayList list = new ArrayList();
51: Type type = criteriaQuery.getTypeUsingProjection(criteria,
52: propertyName);
53: if (type.isComponentType()) {
54: AbstractComponentType actype = (AbstractComponentType) type;
55: Type[] types = actype.getSubtypes();
56: for (int i = 0; i < types.length; i++) {
57: for (int j = 0; j < values.length; j++) {
58: Object subval = values[j] == null ? null : actype
59: .getPropertyValues(values[j],
60: EntityMode.POJO)[i];
61: list.add(new TypedValue(types[i], subval,
62: EntityMode.POJO));
63: }
64: }
65: } else {
66: for (int j = 0; j < values.length; j++) {
67: list.add(new TypedValue(type, values[j],
68: EntityMode.POJO));
69: }
70: }
71: return (TypedValue[]) list.toArray(new TypedValue[list.size()]);
72: }
73:
74: public String toString() {
75: return propertyName + " in (" + StringHelper.toString(values)
76: + ')';
77: }
78:
79: }
|