Results 1 to 2 of 2

Thread: Using Groovy with HibernateTemplate and HibernateCallback

  1. #1
    Join Date
    Sep 2004
    Posts
    5

    Default Using Groovy with HibernateTemplate and HibernateCallback

    Hi all.

    I'm in the early stages of learning Groovy and how to use it in the context of each layer in a typical web application (controllers, services, daos).

    I'm trying to find out the best way of representing the following in Groovy.

    Code:
    return (Integer)getHibernateTemplate().execute(
      new HibernateCallback() {
        public Object doInHibernate(Session session) 
          throws HibernateException,SQLException {
    
          def query = session.createQuery("select count(*) from TestObject");
          return ((Long)query.iterate().next()).intValue();
        }
      });
    }
    I'm sure there is a way to simplify this in Groovy, but I'm having problems with how to represent the HibernateCallback class as a closure. Any help is appreciated.

    -brad

  2. #2
    Join Date
    Jul 2007
    Location
    Shanghai, China
    Posts
    2

    Default maybe this is useful for you

    Code:
    public class GroovyHibernateTemplate extends HibernateTemplate {
    
        public Object execute(boolean exposeNativeSession,final Closure worker){
            return this.execute(new HibernateCallback() {
                
                public Object doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
                    return worker.call(session);
                }
               
            }, exposeNativeSession);
        }
    
        public Object execute(final Closure worker) {
            return this.execute(new HibernateCallback() {
                
                public Object doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
                    return worker.call(session);
                }           
            });
        }
    
        public List executeFind(final Closure worker)  {
            return this.executeFind(new HibernateCallback() {
                
                public Object doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
                    return worker.call(session);
                }   
                
            });
        }
        
    }
    then use it in Groovy like this:
    Code:
    template.execute{ session->
        def query = session.createQuery("select count(*) from TestObject");
        return query.iterate().next();
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •