【发布时间】:2019-08-16 21:20:42
【问题描述】:
在 Grails 中,我希望根据 SQL 查询设置一个瞬态变量。我必须使用 SQL,而不是 HQL。
(这是一个简化的示例。使用 Grails 3.0.11。)
- 执行 SQL 查询
- 作为 SQL 查询的一部分,计算列的值
- 将该值设置在实体类中添加到 SQL 查询中
- 见下方
ofLegalAge/of_legal_age
假设我有以下域类
class Person {
String firstName
String lastName
Integer age
static mapping = {table "person"}
}
然后我对 Person Domain 类的看法如下
class PersonView {
Long id
String firstName
String lastName
// ofLegalAge is dynamically set based on query
Boolean ofLegalAge
// Other things based on joins
static transients = [ "ofLegalAge" ]
static mapping = {table "person_view"}
}
我想做的是
String sql = """select id,
first_name,
last_name,
-- This is the source for of_legal_age
case when age >= :ageForThisArea
then true
else false
end as of_legal_age
from view_person
where age >= :ageForThisArea"""
def session = sessionFactory.getCurrentSession()
def query = session.createSQLQuery(sql)
query.setParameter("ageForThisArea", age)
query.addEntity(PersonView)
// This should result in a List of PersonView with ofLegalAge set correctly
List<PersonView> theList = query.list()
基本上最后我需要根据查询设置ofLegalAge,但是最后(在调用query.list() 之后)它没有在PersonView 中设置。
【问题讨论】:
-
@Vahid 谢谢,但是 (a) PersonView 类已存在并用于许多其他事情,并且 (b) 正如我所提到的,我需要 SQL 用于与此问题分开的查询的其他部分
-
想知道如果您将其更改为字符串是否可行?你可以尝试 CAST(1 AS BIT) ELSE CAST(0 AS BIT) END 按照stackoverflow.com/questions/10377781/…
标签: grails grails-orm transient