Search code examples
hibernategrailsnullpointerexceptiongrails-orm

Grails createCriteria returning null criteria


I'm getting a strange NullPointerException in grails 2.1.1.

HibernateCriteriaBuilder crit = FattoriIndicatori.createCriteria()
crit.createAlias("indicatori","ind")... // NPE here, because underlying Criteria is null
  • the class is listed in hibernate-cfg
  • other classes from the same config file work just right
  • the class not been added recently, it's there since a long time

Surely something is missing, but I can't see it.

Edit: I am sure that the class is correctly configured beacuse this code works:

HibernateCriteriaBuilder crit = FattoriIndicatori.createCriteria()
Number res = crit.get {
projections {
    count()
    }
}

Solution

  • The problem is that certain methods on HibernateCriteriaBuilder only work when called from within the closure passed to get, list, etc.

    HibernateCriteriaBuilder crit = FattoriIndicatori.createCriteria()
    def results = crit.list {
      createAlias("indicatori","ind")
      eq('ind.something', 'value')
    }
    

    will work fine. The list method does some initialization (including creating the underlying Criteria instance, which is initially null), then calls the closure to build up the criteria specification, then executes the resulting query and returns the results.