0

This is my user.java domain class is

public class User {

private Integer iduser;
private String user_name;
private String user_activation_key;
private String user_password;
private String user_email;
private Character registered;

public Integer getIduser() {
    return iduser;
}

public void setIduser(Integer iduser) {
    this.iduser = iduser;
}

public String getUser_name() {
    return user_name;
}.....more code

And in a another Test class I have Coded as follow.

SQLQuery query = session.createSQLQuery("select * from user");
List<User> availableUsers = new ArrayList<User>();
availableUsers=(List<User>)query.list();

query is a SQLQuery (Hibernate implementation) to get user list from DB.
But I can't cast the (query.list) to List<User>.
I'm getting class cast exception. availableUser is a object list.
What steps should I follow.

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
Amila Iddamalgoda
  • 4,166
  • 11
  • 46
  • 85

2 Answers2

2

Use HQL

SQLQuery query = session.createQuery("from User"); //note here User is POJO class name
List<User> availableUsers = new ArrayList<User>();
availableUsers=(List<User>)query.list();  

18.1.1. Scalar queries

These will return a List of Object arrays (Object[]) with scalar values for each column in the user table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

Use addScalar() method when using createSQLQuery see more

Community
  • 1
  • 1
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
1

query.list() returns List<Object>. Each object is actually an Object array (Object[]) which has the whole row.

For example, if you are getting all the Employee results, then the list is as follows:-

{ {emp_id,emp_name,other_emp_col} , {emp_id,emp_name,other_emp_col}, {emp_id,emp_name,other_emp_col} ....}

So for retrieving them you will have to iterate the list of Object and cast iterator.next() into an Object array and then construct your own User object.

For example:-

List<Object> userList = query.list();

Iterator<Object> itr = userList.iterator();
while(itr.hasNext()){
    Object[] userRow = (Object[]) itr.next();
    User userObj = new User();
    userObj.setName(userRow[0]);

}

To save all these efforts as Aniket said, use HQL

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Madhura
  • 551
  • 5
  • 18