简体   繁体   English

使用where子句在hibernate中选择查询

[英]select query in hibernate with where clause

I have class Login which has userId , username and password . 我有类登录,其中包含userIdusernamepassword

For a user to login I am checking username and password and geting userId . 对于用户登录,我正在检查usernamepassword以及geting userId If userId is not zero then it will lead to home page. 如果userId不为零,那么它将导致主页。 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();
    }

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 1)您正在使用HQL,因此您需要了解您不能在HQL查询的投影中给出数据库中的列名

 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. 在您的Login类中,您没有user_id字段,并且您将user_id给投影。 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. HQL映射类与数据库,因此Login类将登录表,userId字段将是数据库中的user_id列。您编写的是纯SQL查询而不是HQL查询。

Please use this HQL query. 请使用此HQL查询。

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. 这里的log是别名,就像我们在普通Java中所做的那样。

Login log=new Login()
log.userId

设置参数时尽量不要使用冒号。

query.setParameter("userName", login.getUserName());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM