Gorm equivalent for SQL

天涯浪子 提交于 2019-12-24 09:58:02

问题


Simple one - what is the best way in Grails/Gorm to get the same effect as this SQL query:

SELECT YEAR(date) as SalesYear, MONTH(date) as SalesMonth, SUM(Price) AS TotalSales FROM Sales GROUP BY YEAR(date), MONTH(date) ORDER BY YEAR(date), MONTH(date)


回答1:


The executeQuery method of a domain class allows you to run HQL queries.

If you look at some examples, you will notice that the Hibernate Query Language remembers a lot SQL, but is object-oriented.

From the Grails docs:

The executeQuery method allows the execution of arbitrary HQL queries. HQL queries can return domain class instances, or Arrays of specified data when the query selects individual fields or calculated values.

So in your case, the query will return an array of the specified data, since don't matches with a Domain Class, but you will be able to iterate over this data.

Assuming that you mapped your sales table as Sales domain class:

class Sales {
  Date date
  BigDecimal price
  ...
  static mapping = {
    ...
  }
}


def result = Sales.executeQuery("SELECT YEAR(date) as SalesYear, MONTH(date) as SalesMonth, SUM(Price) AS TotalSales FROM Sales GROUP BY YEAR(date), MONTH(date) ORDER BY YEAR(date), MONTH(date)")

//iterate over the result
result.each { sales ->
  println sales[0] //year
  println sales[1] //month
  println sales[2] //total
}


来源:https://stackoverflow.com/questions/13464500/gorm-equivalent-for-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!