Select a request in sleep mode with a where clause

I have a Login class that has userId , username and password .

To enter the userโ€™s system, I check username and password and get userId . If userId not equal to zero, this will lead to the home page. I am trying to do this in sleep mode. But my request 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(); } 
+5
source share
2 answers

1) You are using HQL, so you need to understand that you cannot specify the names of columns that are in the database in the projections of the 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 a field like user_id , and you gave user_id to the predictions. HQL maps the class to the database, so the Login class will have an entry table, and the userId field will have the user_id field in the database. And what you wrote is a simple SQL query, not a 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 an alias, as in normal Java.

 Login log=new Login() log.userId 
+6
source

Do not try to use a colon by specifying a parameter.

 query.setParameter("userName", login.getUserName()); 
+2
source

Source: https://habr.com/ru/post/1207285/


All Articles