select query in hibernate with where clause
hibernate, java, mysql
Solution
1) You are using HQL, so you need to understand that you can't give column names which are in database in projections of HQL query
String hql = "select user_id from login where user_name= :username and
password= :password";
Here in your Login class you don't have field as `user_id` and you gave `user_id` into projections. HQL maps class with database, hence Login class will login table and userId field will be user_id column in database.And what you wrote is plain SQL query not HQL query.
Please use this HQL query.
String hql="Select log.userId from Login log where log.username=:username and log.password=:password"
Here log is alias name like we do in plain Java.
Login log=new Login()
log.userId
Problem
I have class Login which has `userId`, `username` and `password`. For a user to login I am checking `username` and `password` and geting `userId`. If `userId` is not zero then it will lead to home page. I am trying to do this in hibernate. But my query is not working ``` public int userLogin(Login login) throws MySQLIntegrityConstraintViolationException, SQLException, Exception { Session session = HibernateUtil.getSessionFactory().openSession(); int userId = 0; try { session.beginTransaction(); String hql = "Select log.userId from Login log where log.userName=:userName and log.password=:password"; System.out.println(hql); Query query = session.createQuery(hql); query.setParameter(":userName", login.getUserName()); query.setParameter(":password", login.getPassword()); List result = query.list(); System.out.println("resultset:"+result); Iterator iterator = result.iterator(); while(iterator.hasNext()){ userId = (int) iterator.next(); } } catch (HibernateException e) { if (session.getTransaction() != null) { session.getTransaction().rollback(); } } finally { session.close(); } ```