简体   繁体   中英

Issue in HQL queries?

This is a test program. Table in the database is student with id and name as columns. POJO class is Student with id and name as properties

HQL query used in servlet1 is:

List<Student> l = ses.createQuery("select s.id, s.name from Student s").list();

        out.println("Database students are as follows:<br/>");
        Iterator it= l.iterator();
        while(it.hasNext())
        {
            Object o[]= (Object[]) it.next();
            out.println("Student id is :"+o[0]);
            out.println("<br/>");
            out.println("Student name is :"+o[1]);
            out.println("<br/>");
        } 

HQL query in servlet2 is:

List<Student> l=ses.createQuery("from Student").list();
        out.println("Database students are as follows:<br/>");
        Iterator it= l.iterator();
        while(it.hasNext())
        {
            Student s= (Student) it.next();
            out.println("Student id is :"+s.getId());
            out.println("<br/>");
            out.println("Student name is :"+s.getName());
            out.println("<br/>");
        }

In servlet1 if i use Student object instead of Object class object the data is not retrieved from the database why?, viceversa everything works fine.

In sevlet2 if i use Object class object instead of Student object the data is not retrieved from the database why?, viceversa everything works fine.

Because when you are calling l=ses.createQuery("from Student").list(); you are retrieving the full set of columns from the DB and there the Student class can be properly instantiated.

Servlet 1 & 2:

 List<Student> l = ses.createQuery("select s.id, s.name from Student s").list();

that query is return list of object,so you need mentioned what kind of Object your are going to retrive.

it return Student < Id , Name > Object

 ses.createQuery("select s.id, s.name from Student s").list();

if your trying to use

 List<Object> it also return your Student(base object of list) Object.but it not good.so,we specifically mentioned what exact format Object type.

both cases,your need to perform Casting Operation.

 List<Student> l =(List<Student>) ses.createQuery("select s.id, s.name from Student s").list();
 List<Object> l =(List<Object>) ses.createQuery("select s.id, s.name from Student s").list();

Your first query has multiple clause that you could not convert to List because id and name are different type. So it will be List type.

For your second query, you are returning list of student so you should not convert it to Object type then back to Student type again. For more information please follow link here- https://weblogs.java.net/blog/2007/04/25/java-persistence-query-return-types .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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