Grails - 同时发生多个用户保存

时间:2018-02-28 02:45:33

标签: grails gorm

在此情景中,用户A 提交日期范围(Sun Feb 25 00:00:00 PHT 2018至Mon Feb 26 00:00:00 PHT)的表单2018),同时用户B 提交与用户A 具有相同日期范围的表单。我已经有了一项服务来检查日期范围是否已经使用过,如果用户B 提交表单的时间晚于用户A ,问题就在于两者都提交表格同时检查员似乎没有工作。我使用 PostgreSQL 作为我的数据库

域类:

/** Date Start */
Date dateStart
/** Date End */
Date dateEnd

控制器方法:

def someService

def saveDate() {
    def dateMap   = [:]
    def dateEnd   = Date.parse('MM-dd-yyyy', params?.dateEnd) : null
    def dateStart = Date.parse('MM-dd-yyyy', params?.dateStart) : null

    /** Validate if date exists */
    def dateExists = someService.checkDate(dateStart, dateEnd)

    //.. 

    if (dateExists) {
        flash.error = message(code: "Date Exists")
    } else {
        dateMap = [
            dateStart : dateStart
            dateEnd   : dateEbd
        ]

        def saveInstance = someService.saveDateRange(dateMap)

        if (saveInstance) {
            flash.error = message(code: "Success")
        }
    }
    //..
}

服务:

def checkDate(Date dateStart, Date dateEnd) {
    def periodQuery = SomeDomain.executeQuery("SELECT d.dateStart, d.dateEnd FROM SomeDomain d")

    periodQuery.each { val ->
        def convertedDateStart = new Date(val[0].getTime())
        def convertedDateEnd   = new Date(val[1].getTime())

        if (dateStart == convertedDateStart && dateEnd == convertedDateEnd) {
            return true
        }
    }

    return false
}

def saveDateRange(Map dateMap) {
    def saveInstance = new SomeDomain()

    saveInstance.with {
        dateStart = dateMap?.dateStart
        dateEnd   = dateMap?.dateEnd
    }

    saveInstance.save(flush: true, failOnError: true)

    return saveInstance
}

0 个答案:

没有答案