tags:

views:

66

answers:

3

I have this method signature:

public int nrOfEntities(Class<? extends MailConfirmation> clazz, User user, String email)

I would like nrOfEntities to return the number of entities that:

  • Are of the concrete class clazz
  • Have a matching User if user != null
  • Have a matching email if user == null

It's the class matching I'm having a problem with. I've tried a few statements without any luck.

A: 

If you want to test the class of an object, you should be able to use something like the following:

Object entity = ... // Get the entity however
boolean matchesClass = entity.getClass().equals(clazz);

If this isn't working for you, give some examples of how it fails since it should be this straightforward!

Andrzej Doyle
Of course that would match. But I want to fetch Hibernate entities of the class clazz.
DeletedAccount
+1  A: 

Are you looking for "from " + clazz.getSimpleName() + " where ..."?

Robert Munteanu
It should work, but I prefer waxwing's answer as using the Criteria API seems nice when constructing this type of query at runtime. Thank you for answering though! (I upvoted it too of course.)
DeletedAccount
True, the Criteria API is better for this kind of queries than HQL.
Robert Munteanu
+2  A: 

Can clazz have subtypes that should not be counted?

If not, is it not sufficient to create the query on clazz?

Criteria criteria = session.createCriteria(clazz);
if (user == null) {
    criteria.add(Restrictions.eq("email", email);
} else {
    criteria.add(Restrictions.eq("user", user);
}
int result = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();

Now I am guessing how your mapping looks (that there are "email" and "user" properties).

If that is not working, I know that there is a pseudo property named "class", at least in HQL. Maybe you can experiment with that.

waxwing
Ah, excellent. I spent 5 minutes looking for the pseudo property but couldn't find it. Using the Criteria API was new ground for me, worked great though. Thank you!
DeletedAccount