Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not equal query in hql not work

I am tring the 'not equal' query in 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    |                |
+-------------+--------------+------+-----+---------+----------------+
like image 466
SamanthaJeyakumar Avatar asked Mar 04 '15 19:03

SamanthaJeyakumar


1 Answers

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.

like image 183
lsrom Avatar answered Oct 09 '22 01:10

lsrom