Grails criteria query : ‘createAlias’ made it easy

17 / Jan / 2011 by Amit Jain 2 comments

Hello friends,

In my grails project, I was finding it difficult to write a query using criteria which can be read as ‘list all customers whose current account balance is more than minimum account balance of that customer’. The simplified form of the domain is given below :

class Customer {
   String name
   Account account
   BigDecimal minAccountBalance
   ...
}

class Account {
   BigDecimal currentBalance
   ...
}

As far as my understanding goes, criteria provides comparison between the fields in the same domain but I needed to compare values between two domains. After spending some time on it, I could make it work using ‘createAlias’ statement. Before you go through the query, please have a look at one of the nice blog written by Rob Fletcher which is available here to understand what ‘createAlias’ does.

Here is the query :

Customer.createCriteria().list(){
      createAlias('account', 'acc')
      gtProperty('acc.currentBalance', 'minAccountBalance')
    }

Hope this helped!

Cheers!

~~Amit Jain~~
amit@intelligrape.com

http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a comment -