Oliver
Oliver

Reputation: 117

Grails findById( null ) returning "random" result

I found a very strange behavior in our grails application today that i want to share with you.

We are using grails 2.3.11 on mysql 5.1.48.

We had a DomainObject.findById( id ) in one of your Controller actions. We failed to check the id for a null value so DomainObject.findById( null ) would be called when no id is passed as an argument.

Normally DomainObject.findById( null ) will return null but there is a special condition that will yield other results!

If the controller action called before that inserted a new record in the database (lets call it Object B), regardless of the domain object stored, the DomainObject.findById( null ) will find the DomainObject with the same Id the Object B got on insert.

So when the controller action called before saved anything the findById(null) will return a row. And that row will have the same id the last inserted element got.

I am totally aware that using findById(null) is not the desired way to do it but I was quite shocked about the results it yielded. But returning any seemingly "random" result seems very strange to me.

I also want to note that DomainObject.get(null) will not suffer from this problem.

Anybody else witnessed this?

There is an active Jira pointing in this direction: https://jira.grails.org/browse/GRAILS-9628 but its not really describing this issue.

Upvotes: 0

Views: 942

Answers (2)

Oliver
Oliver

Reputation: 117

Thx for your information scot.

I have further details. This behaviour is also altered by the underlying database. While mysql suffers from this, maria-db (a mysql clone) does not!

So what happens is bound to the underlying database system. That should not happen to an abstraction layer ....

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27200

We don't really support passing null as an argument to a dynamic finder like that. Dynamic finders have explicit support for querying by null. Instead of DomainClass.findByName(null) you would call DomainClass.findByNameIsNull(). If you have a reference that may or may not be null, instead of passing that as an argument to a dynamic finder, the code can almost always be made cleaner by writing a criteria query or a "where" query that has a conditional in it.

I hope that helps.

Upvotes: 0

Related Questions