简体   繁体   English

如何在Grails中调用命名查询

[英]How To Call A Named Query In Grails

Given the following example from Hibernate Make Easy , how can I call the named query, user.findByLoginName in Grails? 给定以下来自Hibernate Make Easy的示例 ,如何在Grails中调用命名查询user.findByLoginName?

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 {     }

You have to use the Hibernate session. 您必须使用休眠会话。

In Grails 1.1 you can use the withSession method of the class. 在Grails 1.1中,可以使用该类的withSession方法。

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. 使用Grails 1.0,您需要将sessionFactory对象注入到Controller / Service中以对其进行访问。

1.2 is introducing named query support as part of a closure inside your domain objects. 1.2引入了命名查询支持,作为域对象内部闭包的一部分。 That should make this easier. 那应该使这更容易。

From: http://www.grails.org/1.2-M3+Release+Notes 来自: 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 这是文档: http : //grails.org/doc/latest/ref/Domain%20Classes/namedQueries.html

Sounds like ability to pass in parameters is slated for 1.2RC1. 听起来像传递参数的能力对于1.2RC1而言已定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM