Grails GORM : SELECT AS

北城余情 提交于 2019-12-20 04:38:35

问题


I'm trying to get all the Users that are born today with GORM but I'm failing to write this query in Grails:

SELECT
DAY(dateOfBirth) AS 'day',
MONTH(dateOfBirth) AS 'month'
FROM Users
WHERE day = '...' AND month = '...';

... will be replaced with today's values.

Minimal User Domain class

class User {

  Date dateOfBirth

  ...

}

Minimal UserService class

@Transactional
class UserService {

  def getTodayBirthdays() {

    def bornTodayQuery = User.where{
      /* I'm thinking here I must
       * select the DAY and MONTH from the DB
       * and compare it with the today ones.
       */
    }       

    User usersBornToday = bornTodayQuery.findAll()      

    usersBornToday      

  }

}

Any ideas how can I do an alias (SELECT field AS alias) with GORM?

I'm using:

  • Grails 2.4.4

Thanks!


回答1:


You could use a where query in your service:

@Transactional(readOnly = true)
def listBirthday(int _month, int _day) {
  // Calendar.JANUARY equals to zero!
  def m = _month + 1
  // Run a where query on the users
  User.where {
    month(dateOfBirth) == m && day(dateOfBirth) == _day
  }
}

@Transactional(readOnly = true)
def listBirthdayToday() {
  def cal = Calendar.getInstance()
  listBirthday(cal.get(cal.MONTH), cal.get(cal.DAY_OF_MONTH))
}

In addition to month and day there are some other functions, here is the documentation (look for "Other Functions")



来源:https://stackoverflow.com/questions/29130921/grails-gorm-select-as

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