使用where子句在冬眠中选择查询

使用where子句在冬眠中选择查询

本文介绍了使用where子句在冬眠中选择查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Login类,它具有userIdusernamepassword.

I have class Login which has userId, username and password.

要让用户登录,我正在检查usernamepassword并获得userId.如果userId不为零,则将进入主页.我正在尝试在休眠状态下执行此操作.但是我的查询无法正常工作

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();
    }

推荐答案

1)您正在使用HQL,因此您需要了解,不能为HQL查询的投影中的数据库提供列名

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";

在您的Login类中,您没有作为user_id的字段,而是将user_id放入了投影中.HQL将类与数据库映射,因此Login类将登录表,而userId字段将是数据库中的user_id列.您编写的是普通SQL查询而不是HQL查询.

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.

请使用此HQL查询.

String hql="Select log.userId from Login log where log.username=:username and log.password=:password"

这里的日志是别名,就像我们在普通Java中一样.

Here log is alias name like we do in plain Java.

Login log=new Login()
log.userId

这篇关于使用where子句在冬眠中选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:12