Hibernate SQL自连接技术总结

在PL/SQL中执行SQL一下自连接语句:
select o.fullname_,p.fullname_ from fw_organization_view o left join fw_organization_view p on o.parentid_=p.id_ where o.id_=30004;
可以正常执行得到结果:当前组织全称,父组织全称
但在Hibernate中执行以上脚本

StringBuffer sql=new StringBuffer("select o.fullname_,p.fullname_ from fw_organization_view o left join fw_organization_view p on o.parentid_=p.id_ where o.id_=:id");
Query query = this.getSession().createSQLQuery(sql.toString());
query.setLong("id", id);
List list = query.list();
Object[] obj = list.get(0);

得到结果
obj[0]=当前组织全称
obj[1]=当前组织全称
解决方案:把父组织全称加上别名可以得到预期的效果
将代码修改为

StringBuffer sql=new StringBuffer("select o.fullname_,p.fullname_ as parentName from fw_organization_view o left join fw_organization_view p on o.parentid_=p.id_ where o.id_=:id");
Query query = this.getSession().createSQLQuery(sql.toString());
query.setLong("id", id);
List list = query.list();
Object[] obj = list.get(0);

这样得到结果为
obj[0]=当前组织全称
obj[1]=父组织全称

你可能感兴趣的:(通用技术)