coderberry

Using Criteria Builder With Projections

Something I had to dig around for today was how to perform a sum on a table using Criteria Builder. It seems that it is treated a bit different than a normal query would be. Here is an example of what I tried and failed at:

1
2
3
4
5
6
7
8
9
10
11
12
def c = Transaction.createCriteria()
def cnt = c.get {
  projections {
    sum("amount")
  }
  and {
    eq("status", k)
    eq("transactionType", transactionType)
    ge("dateTimeProcessed", cal1.getTime())
    le("dateTimeProcessed", cal2.getTime())
  }
}

After playing around with it a bit, I found that I can’t use the ‘and’ closure. I revised the code to the following and it worked:

1
2
3
4
5
6
7
8
9
10
def c = Transaction.createCriteria()
def cnt = c.get {
  projections {
    sum("amount")
  }
  eq("status", k)
  eq("transactionType", transactionType)
  ge("dateTimeProcessed", cal1.getTime())
  le("dateTimeProcessed", cal2.getTime())
}

Comments