mongodbgrailsgrails-domain-class

grails Objects query when hasMany relationship is NULL


Not able to get the list of Objects when a hasMany attribute is null.

Class User {
...
List<EMail> emails
static hasMany = [emails: EMail,... ]
static mappedBy = [emails: 'customer',...]
... 
}

Where Email is another Class with some String Attributes

Now i am trying to make a simple query as:

Method 1:

def users = User.findAllByEmailsIsEmpty()

This is giving Error as:

 Queries of type IsEmpty are not supported by this implementation

Method 2:

def users = User.findAllByEmailsIsNull()

This is giving all the users even those have Email object associated with it.

Then I thought of trying Criteria Query (https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/createCriteria.html )

Method 3:

def userCriteria = User.createCriteria()
    def users = userCriteria.list(){
        sizeEq('emails', 0)
    }

This gives No result ( users.size() is 0 )

Method 4:

def userCriteria = User.createCriteria()
    def users = userCriteria.list(){
        isNull('emails')
    }

This again gives all the Users even those who don't have emails.

Method 5:

 def userCriteria = User.createCriteria()
    def users = userCriteria.list(){
        isEmpty('emails')
    }

This gives the Error : Queries of type IsEmpty are not supported by this implementation

Method 6:

def userCriteria = User.createCriteria()
    def users = userCriteria.list(){
        eq('emails', null)
    }

This again lists down all the users.

PS: Grails is configured with Database as MongoDB.

Solution

  • I would use the grep method. Something like this:

    nullEmailUsers = User.list().grep {
        !it.emails
    }