0

I have a hibernate entity Type like so

@Entity
@Table(name = "type")
public class Type {
  @Column(name = "enabled")
  private boolean enabled = false;
}

and I want to create a function that returns if any row in the Type table has enabled = true. I want to be as efficient as possible by using a projection or criterion but I don't know where to start

Mark
  • 3,137
  • 4
  • 39
  • 76

1 Answers1

1

Maybe the most efficient way to do this is to search for the first row that has enabled = true, and check if it exists.

Criteria crit = session.createCriteria(Type.class);
crit.setProjection(Projections.id());
crit.add(Restrictions.eq("enabled", true));
crit.setMaxResults(1);
boolean anyIsEnabled = crit.uniqueResult() != null;

The query should return result when/if it encounters the first result with enabled = true, so it doesn't have to go through the whole table like a solution using count, for example, would have to.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • thanks, can you just explain the query.uniqueResult() and how that runs the query? the examples I am looking at seem to do crit.list() where you have that – Mark Apr 09 '15 at 16:18
  • ok cool I see your edit, can you tell me the difference between uniqueResult() and list() – Mark Apr 09 '15 at 16:23
  • 1
    Sorry, it should've been `crit.uniqueResult()` instead of `query.uniqueResult()`. Anyway, `list()` returns all matching results, while `uniqueResult()` return single result, or null if nothing is found. It throws exception if there are multiple results, but in this case it is not a problem because of `setMaxResults(1)`. – Predrag Maric Apr 09 '15 at 16:31