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 groovy
.lang
.Closure
;
19 import groovy
.lang
.MissingMethodException
;
21 import java
.util
.regex
.Pattern
;
23 import org
.codehaus
.groovy
.grails
.orm
.support
.TransactionManagerAware
;
24 import org
.hibernate
.SessionFactory
;
25 import org
.springframework
.transaction
.PlatformTransactionManager
;
26 import org
.springframework
.transaction
.TransactionStatus
;
27 import org
.springframework
.transaction
.support
.TransactionCallback
;
28 import org
.springframework
.transaction
.support
.TransactionTemplate
;
31 * @author Graeme Rocher
35 public class WithTransactionPersistentMethod
extends
36 AbstractStaticPersistentMethod
implements TransactionManagerAware
{
38 private static final Pattern METHOD_PATTERN
= Pattern
.compile("^withTransaction$");
39 private static final String METHOD_SIGNATURE
= "withTransaction";
40 private TransactionTemplate transactionTemplate
;
42 public WithTransactionPersistentMethod(SessionFactory sessionFactory
, ClassLoader classLoader
) {
43 super(sessionFactory
, classLoader
, METHOD_PATTERN
);
47 * @see org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractStaticPersistentMethod#doInvokeInternal(java.lang.Class, java.lang.String, java.lang.Object[])
49 protected Object
doInvokeInternal(Class clazz
, String methodName
,
51 if(arguments
.length
== 0)
52 throw new MissingMethodException(METHOD_SIGNATURE
, clazz
,arguments
);
53 if(!(arguments
[0] instanceof Closure
))
54 throw new MissingMethodException(METHOD_SIGNATURE
, clazz
,arguments
);
56 final Closure callable
= (Closure
)arguments
[0];
58 if(transactionTemplate
.getTransactionManager() == null)
59 throw new IllegalStateException("Cannot use method [withTransaction] without a PlatformTransactionManager instance");
61 return transactionTemplate
.execute(new TransactionCallback() {
63 public Object
doInTransaction(TransactionStatus status
) {
64 return callable
.call(status
);
70 public void setTransactionManager(PlatformTransactionManager transactionManager
) {
71 this.transactionTemplate
= new TransactionTemplate(transactionManager
);