hibernate query language or using criteria?

☆樱花仙子☆ 提交于 2019-12-01 11:13:49

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!