Sleeping query language or using criteria?

Anyone who tells me the query using the / hql / sql criteria. The requirement is that the user enters an email address or username, the query returns the user's password from the table user.

+2
java orm hibernate hql criteria
May 25 '10 at 13:55
source share
2 answers

If all you do is select one field, you probably just want to switch to hql (or maybe sql).

If you fulfill the criteria, I believe that you discard the entire object in order to ultimately use a single field.

Edit: This is a very broad question. Here is the tutorial

+1
May 25 '10 at 13:58
source share

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.

+3
May 25 '10 at 14:25
source share



All Articles