Java hql 中的不相等查询不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28862991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:57:59  来源:igfitidea点击:

Not equal query in hql not work

javahibernatehql

提问by SamanthaJeyakumar

I am tring the 'not equal' query in hql.

我在 hql 中搜索“不等于”查询。

 @Override
    public Student findStudentsByYear(String year) {
        String queryString = "from Student where year<>:year ";
        Query query =   sessionFactory.getCurrentSession().createQuery(queryString);        
        query.setParameter("year", year);
        return (Student)query.uniqueResult();
    }

but it is not working properly.How to write this query correctly

但它不能正常工作。如何正确编写此查询

My student table is

我的学生桌是

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| studentId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| course      | varchar(255) | YES  |     | NULL    |                |
| dob         | varchar(255) | YES  |     | NULL    |                |
| email       | varchar(255) | YES  |     | NULL    |                |
| faculty     | varchar(255) | YES  |     | NULL    |                |
| firstName   | varchar(255) | YES  |     | NULL    |                |
| gender      | int(11)      | YES  |     | NULL    |                |
| homeAddress | varchar(255) | YES  |     | NULL    |                |
| lastName    | varchar(255) | YES  |     | NULL    |                |
| linkedIn    | varchar(255) | YES  |     | NULL    |                |
| university  | varchar(255) | YES  |     | NULL    |                |
| year        | varchar(255) | YES  |     | NULL    |                |
| user_userId | bigint(20)   | YES  | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

采纳答案by lsrom

I know it's late but if anyone is having similar problem, you can use this:

我知道为时已晚,但如果有人遇到类似问题,您可以使用以下命令:

Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.ne("year", year));
List<Student> result = criteria.list();

Or this:

或这个:

List<Student> result = session.createQuery ("from Student where year!=:year").setParameter("year", year).list();

I'm not sure what the problem is in above example as Samantha did not provide any information what so ever but my guess is that the uniqueResult()is causing trouble because this query returns a list and not one result.

我不确定上面示例中的问题是什么,因为 Samantha 没有提供任何信息,但我猜测这uniqueResult()是造成问题的原因,因为此查询返回一个列表而不是一个结果。