views:

705

answers:

2

Given the following example from Hibernate Make Easy, how can I call the named query, user.findByLoginName in Grails?

package com.examscam.model;
import javax.persistence.*;
import org.hibernate.Session;
import com.examscam.HibernateUtil;
@Entity
@Table(name = "user", schema = "examscam")
@NamedQuery(name="user.findByLoginName",
   query="from User where loginName = :name" )
public class User {     }
+2  A: 

You have to use the Hibernate session.

In Grails 1.1 you can use the withSession method of the class.

User.withSession { session ->
    return session.getNamedQuery('user.findByLoginName')
        .setString('name', 'someName')
        .list() 
}

With Grails 1.0 you need to inject the sessionFactory object into your Controller/Service to get access to it.

geofflane
+2  A: 

1.2 is introducing named query support as part of a closure inside your domain objects. That should make this easier.

From: http://www.grails.org/1.2-M3+Release+Notes

class Publication {
   String title
   Date datePublished

  static namedQueries = { 
        recentPublications { 
               def now = new Date() 
                gt 'datePublished', now - 365 
        }

        publicationsWithBookInTitle { 
          like 'title', '%Book%' } 
        }
}

Usage

// get all recent publications…  
def recentPubs = Publication.recentPublications()

Here is the doc: http://grails.org/doc/latest/ref/Domain%20Classes/namedQueries.html

Sounds like ability to pass in parameters is slated for 1.2RC1.

Jean Barmash