notes – hibernate ORM Q & A part 1

> Notes – hibernate ORM Q & A

  1. Error on HQL – [Ljava.lang.Object; cannot be cast to com.fndong.entities.Users ?
 private static final String HQL_SELECT_USERS ="select u.uid , u.username,
 u.password from Users u";

public void getUsers(){
List<Users> list = null;
Query query = session.createQuery(HQL_SELECT_USERS);
list = (List<Users>)query.list();
 for(Users h: list){
                    System.out.println("username: " + h.getUsername());
                 }
}

Errors: Ljava.lang.Object; cannot be cast to com.fndong.entities.Users

1.1.) Solutions on Question No. 1 :

You are selecting u.username(which looks like a String), but you are trying to cast that String to your Bean class (Users.java). If you execute an HQL query with a single field, the returned list will contain objects of the type of that field, you are getting a list of String objects.

> If you want to select Bean objects, your query should look like this : CORRECT WAY if we want to cast with Bean

 private static final String HQL_SELECT_USERS ="select u from Users u";

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s