Grails 在数据库优先模式下访问日期相等的数据

Grails accessing data where dates equal in database first mode

在 .Net shop 工作一年后,我将回到 Grails。我一直以代码优先模式编写 Grails。我最新的项目是数据库优先,我以为我已经准备好了。我的 MySql 数据库中有一个简单的日历 table:

commit;CREATE TABLE `Calendar` (
  `ID` bigint(20) NOT NULL,
  `Title` varchar(200) NOT NULL,
  `EventDate` date NOT NULL,
  `StartTime` time DEFAULT NULL,
  `EndTime` time DEFAULT NULL,
  `Location` varchar(500) NOT NULL,
  `version` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在table中有以下数据:

insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('Summer 2016 Garage Sale', '2016-07-23', '7:00 ', '19:00', 'Lodge', 0);

insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('August 2016 Member Meeting', '2016-08-03', '19:00', '20:00', 'Lodge', 0);

commit;

我在 Grails 中的日历 class 看起来像:

package plaquemineelks

import java.sql.Time
import grails.validation.Validateable

@Validateable
class Calendar {

    Long id
    Integer version

    String title
    Date eventDate
    Time startTime
    Time endTime
    String location

    static constraints = {
        title (blank: false)
        eventDate (blank: false)
        location (blank: false)
    }

    static mapping = {
        table "Calendar"
        id column: "ID"
        version column: "version"
        eventDate column: "EventDate"
        startTime column: "StartTime"
        endTime column: "EndTime"
        location column: "Location"
    }
}

我的控制器看起来像:

package plaquemineelks

class CalendarController {

def index() { }

    def getByDate(String EventDate) {
        def Date newDate = Date.parse("mm/dd/yyyy", EventDate)
        def results = Calendar.findAllByEventDate(newDate)
        render(contentType: 'text/json') {[
            'results': results,
            'status': results ? "OK" : "Nothing present"
        ]}
    }
}

当我 运行 应用程序并打开 URI

http://localhost:8080/PlaquemineElks/Calendar/getByDate?EventDate=07/23/2016

我的 Json 看起来像:

{"results":[],"status":"Nothing present"}

日期我试过多种格式等,保留groovy。我确定我遗漏了一些简单的东西。

感谢您的帮助。

您正在使用 sql 查询向 table 插入数据,这意味着默认情况下 StartDate 仅包含日期,00:00:00 包含时间戳。否则,如果您使用 GORM 插入时区,它也会考虑时区。

您需要做的第一件事是为您的应用程序将时区设置为 UTC。在 Bootstrap.grooy 中:

TimeZone.setDefault(TimeZone.getTimeZone('UTC'))

其次你用来解析日期的格式mm/dd/yyyy是错误的,应该是:MM/dd/yyyy.

println Date.parse("mm/dd/yyyy", "07/23/2016")
Sat Jan 23 00:07:00 UTC 2016 //wrong

println Date.parse("MM/dd/yyyy", "07/23/2016")
Sat Jul 23 00:00:00 UTC 2016 //correct