嗨,我有 3 个表的数据库员工:
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 | |
+---------------+------------+------+-----+---------+-------+
因此,我想编写 HQL 语句以使用 person.lastName 从 person.position 获取数据,并且我使用以下代码来提取这些数据,但没有运气:
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;
}
在这就是它向我展示了这个例外:
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)
您能帮我编写正确的 HQL 语句吗?