1 /* Copyright 2004-2005 the original author or authors.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
15 package org
.codehaus
.groovy
.grails
.orm
.hibernate
.metaclass
;
17 import groovy
.lang
.MissingMethodException
;
18 import org
.codehaus
.groovy
.grails
.commons
.DomainClassArtefactHandler
;
19 import org
.codehaus
.groovy
.grails
.commons
.GrailsApplication
;
20 import org
.codehaus
.groovy
.grails
.commons
.GrailsDomainClass
;
21 import org
.codehaus
.groovy
.runtime
.DefaultGroovyMethods
;
22 import org
.hibernate
.SessionFactory
;
23 import org
.springframework
.beans
.SimpleTypeConverter
;
25 import java
.io
.Serializable
;
26 import java
.util
.regex
.Pattern
;
28 * The "get" static persistent method for Grails domain classes. This method
29 * takes an id and returns the instance
33 * Or an HQL query and tries to retrieve a unique result (note an exception is thrown if the result is not unique)
35 * eg. Account.get("from Account as a where a.id=2)
37 * @author Graeme Rocher
40 public class GetPersistentMethod
extends AbstractStaticPersistentMethod
{
42 private static final Pattern METHOD_PATTERN
= Pattern
.compile("^get$");
43 public static final String METHOD_SIGNATURE
= "get";
44 private GrailsApplication application
;
45 private SimpleTypeConverter typeConverter
= new SimpleTypeConverter();
47 public GetPersistentMethod(GrailsApplication application
, SessionFactory sessionFactory
, ClassLoader classLoader
) {
48 super(sessionFactory
, classLoader
, METHOD_PATTERN
);
49 this.application
= application
;
52 protected Object
doInvokeInternal(final Class clazz
, String methodName
,
54 // if no arguments passed throw exception
55 if(arguments
.length
== 0)
56 throw new MissingMethodException(METHOD_SIGNATURE
, clazz
,arguments
);
57 // if its not a map throw exception
58 Object arg
= arguments
[0];
63 GrailsDomainClass domainClass
= (GrailsDomainClass
) this.application
.getArtefact(
64 DomainClassArtefactHandler
.TYPE
, clazz
.getName());
65 if(domainClass
!= null) {
66 Class identityType
= domainClass
.getIdentifier().getType();
68 if(!identityType
.isAssignableFrom(arg
.getClass())) {
69 if(arg
instanceof Number
&& Long
.class.equals(identityType
)) {
70 arg
= DefaultGroovyMethods
.toLong((Number
)arg
);
73 arg
= typeConverter
.convertIfNecessary(arg
, identityType
);
78 return super.getHibernateTemplate().get( clazz
, (Serializable
)arg
);