2 * Copyright 2004-2006 Graeme Rocher
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.codehaus
.groovy
.grails
.orm
.hibernate
.metaclass
;
18 import grails
.orm
.HibernateCriteriaBuilder
;
19 import groovy
.lang
.Closure
;
20 import groovy
.lang
.MissingMethodException
;
22 import java
.util
.Iterator
;
24 import java
.util
.regex
.Pattern
;
26 import org
.hibernate
.SessionFactory
;
27 import org
.springframework
.beans
.BeanWrapper
;
28 import org
.springframework
.beans
.BeanWrapperImpl
;
31 * Lets you call criteria inline:
33 * books = Book.withCriteria {
35 * inList("author.name",
36 * ["Dierk Koenig", "Graeme Rocher"])
37 * ilike("title", "Groovy")
40 * @author Graeme Rocher
44 public class WithCriteriaDynamicPersistentMethod
extends
45 AbstractStaticPersistentMethod
{
47 private static final Pattern METHOD_PATTERN
= Pattern
.compile("^withCriteria$");
48 private static final String METHOD_SIGNATURE
= "withCriteria";
50 public WithCriteriaDynamicPersistentMethod(SessionFactory sessionFactory
, ClassLoader classLoader
) {
51 super(sessionFactory
, classLoader
, METHOD_PATTERN
);
55 * @see org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractStaticPersistentMethod#doInvokeInternal(java.lang.Class, java.lang.String, java.lang.Object[])
57 protected Object
doInvokeInternal(Class clazz
, String methodName
,
59 if(arguments
.length
== 0)
60 throw new MissingMethodException(METHOD_SIGNATURE
, clazz
,arguments
);
62 Object arg1
= arguments
[0];
63 Object arg2
= arguments
.length
> 1 ? arguments
[1] : null;
65 if(!(arg1
instanceof Closure
&& arg2
== null) && !((arg1
instanceof Map
) && (arg2
instanceof Closure
)))
66 throw new MissingMethodException(METHOD_SIGNATURE
, clazz
,arguments
);
68 HibernateCriteriaBuilder builder
= new HibernateCriteriaBuilder(clazz
, getHibernateTemplate().getSessionFactory());
69 Closure callable
= arg1
instanceof Closure ?
(Closure
)arg1
: (Closure
)arg2
;
71 if(arg1
instanceof Map
) {
72 BeanWrapper builderBean
= new BeanWrapperImpl(builder
);
74 for (Iterator i
= args
.keySet().iterator(); i
.hasNext();) {
75 String name
= (String
) i
.next();
76 if(builderBean
.isWritableProperty(name
)) {
77 builderBean
.setPropertyValue(name
, args
.get(i
));
82 return builder
.invokeMethod("doCall",callable
);