Hi, I have database Staff with 3 tables:
mysql> describe person;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| person_id | bigint(20) | NO | PRI | NULL | auto_increment |
| date | datetime | YES | | NULL | |
| first_name | varchar(255) | YES | | NULL | |
| last_name | varchar(255) | YES | | NULL | |
| position | varchar(255) | YES | | NULL | |
| salary | double | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> describe department;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| department_id | bigint(20) | NO | PRI | NULL | auto_increment |
| dept_name | varchar(255) | YES | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
mysql> describe department_person;
+---------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------+------+-----+---------+-------+
| department_id | bigint(20) | NO | PRI | NULL | |
| person_id | bigint(20) | NO | PRI | NULL | |
+---------------+------------+------+-----+---------+-------+
So, I want to compose HQL statement for getting data from person.position using person.lastName and I've used the following code to exctract this data but without luck:
public List<Person> findPosition(){
Session session =
HiberUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Person> result = session.createQuery("select position from Person p where p.lastName= 'Anderson'").list();
for(Person a : result) {
Hibernate.initialize(a.getDepartmentList());
}
session.getTransaction().commit();
return result;
}
In this was it shows me this exception:
Hibernate: select person0_.position as col_0_0_ from person person0_ where person0_.last_name='Anderson'
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to main.Person
at main.StaffDAO.findPosition(StaffDAO.java:100)
at main.Main.main(Main.java:37)
Can you please help me in composing correct HQL statement?
Well, you're selecting a
position
in your query, and trying to put that in a list of Person. Instead you shouldselect p from Person p where p.lastName= 'Anderson'
.select Person from Person p where p.lastName= 'Anderson'
You are selecting an attribute that holds a VARCHAR(255) but expect it returned as a
List<Person>
. That simply does not compute.You could do