面对`org.hibernate.hql.PARSER`使用executeQuery()方法从Grails中的DB获取数据时出错。请告诉我,我做错了什么?

时间:2015-09-11 06:44:51

标签: hibernate grails gorm

我试图根据dateTime获取数据,但我面临一些问题我的查询在MySql中工作,但在Grails中它给出了以下错误:

2015-09-11 11:59:00,697 ERROR org.hibernate.hql.PARSER:56 line 1:182: unexpected token: airDuration 2015-09-11 11:59:00,709 ERROR grails.app.controllers.com.my.test.rest.ipg.ChannelController:200 Invalid device parameter request : org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: airDuration near line 1, column 182 [ from com.my.test.ipgData.ChannelSchedule where channel = 77 and ((airDate between '2015-09-29 05:30:00' and '2015-09-29 20:30:00') or ((airDate + INTERVAL airDuration MINUTE) between '2015-09-29 05:30:00' and '2015-09-29 20:30:00')) order by airDate asc ]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: airDuration near line 1, column 182 [ from com.my.test.ipgData.ChannelSchedule where channel = 77 and ((airDate between '2015-09-29 05:30:00' and '2015-09-29 20:30:00') or ((airDate + INTERVAL airDuration MINUTE) between '2015-09-29 05:30:00' and '2015-09-29 20:30:00')) order by airDate asc ]

以下是我的代码:

ArrayList<ChannelSchedule> channelSchedule;

Date currentDateAndTime = new Date();
String scheduleQuery =  " from " +
                        "     ChannelSchedule " +
                        " where " +
                        "     channel = 77 and ((airDate between '2015-09-29 05:30:00' and '2015-09-29 20:30:00') or ((airDate + INTERVAL airDuration MINUTE) between '2015-09-29 05:30:00' and '2015-09-29 20:30:00')) " +
                        " order by airDate asc " ;

channelSchedule = ChannelSchedule.executeQuery(scheduleQuery);

ChannelSchedule类:

class ChannelSchedule {

    Date airDate;
    String airTime;
    int airDuration;
}

2 个答案:

答案 0 :(得分:0)

您可以定义派生属性(与java中的@Formula相同)

class ChannelSchedule {

    Date airDate;
    String airTime;
    int airDuration;
    static mapping = {
         endTime formula: 'airDate + INTERVAL airDuration MINUTE'
    }
}

并在查询中使用endTime

查看更多here

答案 1 :(得分:0)

如果略微更改逻辑,则不必依赖SQL间隔。你绝对应该使用真实日期而不是字符串

ArrayList<ChannelSchedule> channelSchedule;

Date start
Date end = //Wherever this comes from
use( TimeCategory ) {
    start = /* Wherever the start comes from */ - 5.minutes
}


String scheduleQuery =  " from " +
                        "     ChannelSchedule " +
                        " where " +
                        "     channel = 77 and airDate between :start and :end " +
                        " order by airDate asc " ;

channelSchedule = ChannelSchedule.executeQuery(scheduleQuery, [start: start, end: end]);