grails createCriteria用于日期计算

时间:2016-09-30 04:34:37

标签: grails gorm

我正在尝试使用criteria

从数据库中获取数据

Domain class发票 -

class Invoice{
    Date invoiceNo
    Date invoiceDate
    int interval

    static constraints = { }
    }
来自criteria

controller模块

if(!params.sort && !params.order) {
            params.sort = "invoiceDate + interval" //invoiceDate+ interval
            params.order = "asc"
        }
        def c = Invoice.createCriteria()
        def results = c.list(params) {
            between("invoiceDate+ interval", invoiceDate, invoiceDate+ interval)

        }

我想从dueDate&中计算invoiceDate interval

我想要一个像这样的结果

invoiceNo | invoiceDate | interval| dueDate    |
001       | 2016-09-30  | 5       | 2016-10-05 |
002       | 2016-09-15  | 5       | 2016-09-20 |

1 个答案:

答案 0 :(得分:1)

我会坚持要求您修改Domain class以添加derived field,如下所示。

已修改Domain class - 添加派生字段dueDate

class Invoice{
Date invoiceNo
Date invoiceDate
int interval

//new field added
Date dueDate //Derived filed- will not persisted to the database

static mapping = {
   //formula to calculate dueDate (invoiceDate + interval)
    dueDate formula:"ADDDATE(invoice_date, interval)"
}

static constraints = { }
}

criteria代码段 - 用于获取dueDate介于current Datecurrent Date + 7之间的发票。

def criteria = Invoice.createCriteria()

   Date currentDate =  new Date()

   //fetching data based on the criteria
   List invoiceList = criteria.list {
         between('dueDate', currentDate, (currentDate + 7))
     }