问题
Any one who tell me the query using criteria/hql/sql. Requirement is that user enter email or username the query return the password of the user from table user.
回答1:
If all you're doing is fetching one field, you probably just want to go hql (or possibly sql).
If you do criteria, I believe you're pulling back the entire object, just to eventually use one field.
Edit: That's a really broad question. Here is a tutorial
回答2:
The Criteria API is very appropriate for dynamic query generation and would have my preference here. You could 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();
Note that I'm a bit extrapolating but you shouldn't store clear passwords in database and you shouldn't send passwords by email (which is unsecure by nature). Actually, a common procedure for password recovery is to send a link with a limited lifetime by mail allowing the user to enter a new password.
Update: Actually, you may not need a dynamic query here but I'm leaving the above for reference.
To implement an 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 could run the following query:
from User s
where u.username = :usernameOrPassword
or u.password = :usernameOrPassword
In this case, it doesn't matter which solution you choose, both will do the job.
来源:https://stackoverflow.com/questions/2905273/hibernate-query-language-or-using-criteria