The criteria API is very suitable for generating dynamic queries and will have my preference here. You can do something like this:
Criteria criteria = session.createCriteria(User.class) .setProjection(Projections.property("password")); if (email != null) { criteria.add(Expression.eq("email", email)); } if (username != null) { criteria.add(Expression.eq("username", username)); } String password = (String) criteria.uniqueResult();
Please note that I extrapolate a little, but you should not store clear passwords in the database, and you should not send passwords by e-mail (which is inherently unsafe). In fact, the usual procedure for password recovery is to send a link with a limited lifetime by mail, allowing the user to enter a new password.
Refresh . You may not actually need a dynamic query, but I leave it above for reference.
To implement OR with the Criteria API, you can do something like this:
Criteria criteria = session.createCriteria(User.class); Criterion username = Restrictions.eq("username", usernameOrPassword); Criterion email = Restrictions.eq("email", usernameOrPassword); LogicalExpression orExp = Restrictions.or(username, email); criteria.add(orExp);
In HQL, you can run the following query:
from User s where u.username = :usernameOrPassword or u.password = :usernameOrPassword
In this case, it does not matter which solution you choose, both will do the job.
Pascal Thivent May 25 '10 at 14:25 2010-05-25 14:25
source share