froi
froi

Reputation: 7788

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?

Upvotes: 1

Views: 1771

Answers (2)

quindimildev
quindimildev

Reputation: 1280

Yo can do Person.countByName('Manuel')

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

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=?

Upvotes: 3

Related Questions