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();
}
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.
HQL From: HQL From is same as select clause in SQL, from Employee is same as select * from Employee . We can also create alias such as from Employee emp or from Employee as emp . HQL Join : HQL supports inner join, left outer join, right outer join and full join. For example, select e.name, a.
CreateQuery: Used to create an HQL. createNamedQuery: Used to define queries with name in mapping file or annotation. See this. createNativeQuery: Used to execute native/pure SQL queries.
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
Try not use colon while setting the param.
query.setParameter("userName", login.getUserName());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With