LJ Dee
LJ Dee

Reputation: 87

Grails GORM findAll returns null collection

Consider the following domain models:

class Sales{
    String salesInvoice
    Customer customer
}

class Customer{
    int customerNumber
    String name
}

The problem: I am trying to retrieve all the sales given a customer. Thus the code:

def sales = Sales.findAllByCustomer(Customer.get(params.id))

I don't have problem with getting the customer. But when I use println sales.dump() I get something like

<java.util.ArrayList@d3a25f8 elementData=[mypackage.Sales : null, mypackage.Sales : null] size=2 modCount=3>

If I understand correctly, this means that the query was able to get a list of Sales but what I don't quite understand is why is it returning a list of nulls? I've tried eager fetching but I don't think that will work in this particular problem. So how to I get a list of non-null Sales objects?

Upvotes: 0

Views: 3054

Answers (1)

Chris
Chris

Reputation: 8109

The objects you have shown are not NULL, but the id of the objects is currently NULL: Each grails domain object has a toString() method which will print ${name of the class} : ${id of the instance}. If you receive outputs, like you have shown, it generally means, that your instances are existing (otherwise a NPE would have been thrown!), however the id is not yet fetched from the DB.

  1. I guess you are creating the objects in the code before. You need to flush the context, otherwise id's are not created.
  2. You should declare, that your Sale belongs to a Customer. http://grails.org/doc/latest/guide/GORM.html#manyToOneAndOneToOne

BTW: Name you domain classes in singular. So rename Sales to Sale.

Upvotes: 3

Related Questions