将 SQL 查询转换为 Grails
Posted
技术标签:
【中文标题】将 SQL 查询转换为 Grails【英文标题】:Translating SQL query to Grails 【发布时间】:2017-09-29 17:28:22 【问题描述】:如何将以下 3 表 SQL 查询转换为 Grails?
SELECT t.name, count(*) as c
FROM topic t
LEFT OUTER JOIN article_topics at
ON t.id = at.topic_id
LEFT OUTER JOIN article a
ON at.article_id = a.id
GROUP BY t.name
我一直在尝试类似于但不确定如何进行连接
def criteria = Topic.createCriteria()
criteria.list
groupProperty("name")
projections
count('*')
或者如果我尝试使用它可能会更好/更容易
Topic.executeQuery(..insert sql..)
如果有帮助,我在文章中有文章和主题 GORM 对象
static mapping =
topics lazy: false, joinTable: [name: 'article_topics', column: 'topic_id', key: 'article_id']
【问题讨论】:
当您可以按原样使用 SQL 查询时,为什么还要麻烦这些呢? SQL 查询没有任何问题。 【参考方案1】:托德。在 grails 中,您可以使用 hibernate 本机 sql 查询,如 mr hacki 的 post 中所述。
我分享一个取自生产代码的示例,该示例使用出版物中描述的技术并使用左连接。
List<Map<String, Object>> resumeInMonth(final String monthName)
final session = sessionFactory.currentSession
final String query = """
SELECT
t.id AS id,
e.full_name AS fullName,
t.subject AS issue,
CASE t.status
WHEN 'open' THEN 'open'
WHEN 'pending' THEN 'In progress'
WHEN 'closed' THEN 'closed'
END AS status,
CASE t.scheduled
WHEN TRUE THEN 'scheduled'
WHEN FALSE THEN 'non-scheduled'
END AS scheduled,
ifnull(d.name, '') AS device,
DATE(t.date_created) AS dateCreated,
DATE(t.last_updated) AS lastUpdated,
IFNULL(total_tasks, 0) AS tasks
FROM
tickets t
INNER JOIN
employees e ON t.employee_id = e.id
LEFT JOIN
devices d ON d.id = t.device_id
LEFT JOIN
(SELECT
ticket_id, COUNT(1) AS total_tasks
FROM
tasks
GROUP BY ticket_id) ta ON t.id = ta.ticket_id
WHERE
MONTHNAME(t.date_created) = :monthName
ORDER BY dateCreated DESC
"""
final sqlQuery = session.createSQLQuery(query)
final results = sqlQuery.with
resultTransformer = AliasToEntityMapResultTransformer.INSTANCE
setString('monthName', monthName)
list()
results
希望对你有用
【讨论】:
以上是关于将 SQL 查询转换为 Grails的主要内容,如果未能解决你的问题,请参考以下文章