Search code examples
hibernategrailsgrails-orm

Best way to see if an entity exists in the database given a condition in Grails/Hibernate


What is the best way to see if an entity/domain is already existing in the database given a condition? Wherein the conditions are checked against the attributes of the entity/domain.

The straight forward way is to query them and check, but in my case, I just need to see if one entity satisfies a condition. So I was thinking if there is a another way?


Solution

  • You could issue a query that just returns a count...

    Person.where {
        name == 'Jeff'
    }.count()
    

    That doesn't actually retrieve Person instances. It sends a query to the database that returns the number of instances. For example, if you were using GORM with Hibernate, the generated SQL might look something like this...

    select count(*) as y0_ from person this_ where this_.name=?