最近在项目中采用hibernate执行sql查询的时候,发现一个问题,估计是hibernate的bug,用sql进行多表关联查询的时候,发现hibernate对sql语句的别名支持不是太好,在数据库中执行没有问题的sql语句,一放到程序中就会出错,让人很是郁闷,比如:
select pc.fd_id as fd_id, sc.fd_name as courseName,
tm.fd_name as trainName,tm.doc_creator_id as creator_id,
oe.fd_name as creator, oe1.fd_id as dept_id ,
oe1.fd_name as deptName ,oe2.fd_id as superOrg_id ,
oe2.fd_name as superOrg
from hrt_train_plan_course pc,
hrt_train_main tm ,
hrt_study_course sc,
sys_org_element oe,
sys_org_element oe1,
sys_org_element oe2
where pc.fd_train_main_id = tm.fd_id
and pc.fd_study_course_id =sc.fd_id
and tm.doc_creator_id = oe.fd_id
and tm.doc_dept_id = oe1.fd_id
and oe.fd_parentorgid = oe2.fd_id
sql语句在数据库中执行完全没问题,但是放到org.hibernate.Session.createSQLQuery(sql)中便会报错,fd_name 列找不到的异常,将所有的别名全部去掉,如下:
select pc.fd_id , sc.fd_name ,
tm.fd_name ,tm.doc_creator_id,
oe.fd_name , oe1.fd_id ,
oe1.fd_name ,oe2.fd_id ,
oe2.fd_name
from hrt_train_plan_course pc,
hrt_train_main tm ,
hrt_study_course sc,
sys_org_element oe,
sys_org_element oe1,
sys_org_element oe2
where pc.fd_train_main_id = tm.fd_id
and pc.fd_study_course_id =sc.fd_id
and tm.doc_creator_id = oe.fd_id
and tm.doc_dept_id = oe1.fd_id
and oe.fd_parentorgid = oe2.fd_id
执行该查询不报错,但是所查询出来的数据完全不是在数据库中查询出来的那样,查询出来的fd_name列的值全变成了第一个fd_name的值,即hrt_study_course表fd_name的值,其他表的fd_name值也变成了hrt_study_course表中的fd_name值,最后没办法了,只能采用jdbc查询,或者将第一个sql创建为视图再用hibernate的sql查询。有哪位大神遇到过类似问题并知道答案的,欢迎一起交流。