Hi,
In the 'Hibernate In Action' example page 309, it creates a DAO object (UserDAO) for User lookup. The method getUserById() takes an userId as its input parameter.
My question is in real world user, isn't we often need to find the user based on his/her username, not the id in the database table? This is because user will enter his/her username (not the id generated by database) during login.
So how can I do the getUserById() using the username instead of the database ID?
I think of using HQL to query for the user with the username that I am looking for. But i can't load it the way I can with getUserById().
Is there a better solution?
Thank you.
Code:
public User getUserById(Long userId, boolean lock)
throws InfrastructureException {
Session session = HibernateUtil.getSession();
User user = null;
try {
if (lock) {
user = (User) session.load(User.class, userId, LockMode.UPGRADE);
} else {
user = (User) session.load(User.class, userId);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return user;
}
public User getUserByName(String name)
throws HibernateException {
Session session = HibernateUtil.getSession();
Query q = session.createQuery("select c from User as c where c.name = :name");
q.setString("name", name);