Validation exists in API hibernation criteria

What is the best way to express the query "exists" with hibernation criteria?

In my project, people use counting counts to check if any line matches the criteria (count> 0). To be more efficient, I prefer to use the existing option.

Here is the basic code for calculating by criteria:

public int count(final DetachedCriteria criteria) throws DataAccessException { Object countResult = executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria executableCriteria = criteria.getExecutableCriteria(session); executableCriteria.setProjection(Projections.rowCount()); prepareCriteria(executableCriteria); return executableCriteria.uniqueResult(); } }); if (countResult == null) { countResult = 0; } return (Integer) countResult; } 
+6
source share
1 answer

At one time, I had the same doubts, and I thought it was ineffective. So what I'm doing now, I'm looking for the first match, and it's faster.

 protected boolean exists(final Criteria query) { query.setProjection(Projections.id()); query.setMaxResults(1); return query.uniqueResult() != null; } 

I hope this helps.

+9
source

Source: https://habr.com/ru/post/957408/


All Articles