嗨,我正在尝试联接两个相同的表-sql查询工作正常。
但是当我使用groovy和hibernate在代码中尝试同样的操作时,我遇到了异常。
2015-10-15 16:35:21,084 [http-8083-3] ERROR hql.PARSER - line 1:62: unexpected token: ON
2015-10-15 16:35:21,104 [http-8083-3] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /mips/console/admin/serviceListJSONip - parameters:
_dc: 1444907110958
Stacktrace follows:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ON near line 1, column 62 [from com.company.test.domains.Service s LEFT JOIN Service S2 ON s.parent_id = s2.id where 1=1 and s.serviceType = 'SERVICE' and s.enabled = 1 and cId in (1,2,2,33) order by s.id asc ,rowId asc]
at $Proxy74.createQuery(Unknown Source)
at com.company.test$_closure15.doCall(AdminController.groovy:884)
at com.company.test$_closure15.doCall(AdminController.groovy)
at com.canvas.mips.controllers.SecureController.invokeMethod(SecureController.groovy)
at com.company.test$_closure20.doCall(AdminController.groovy:1030)
at com.company.test$_closure20.doCall(AdminController.groovy)
at org.grails.jaxrs.web.JaxrsFilter.doFilterInternal(JaxrsFilter.java:46)
at java.lang.Thread.run(Thread.java:662)
Hibernate:
我使用的是Grails的旧版本,即1.3,这也是我的代码段,因此在这里
results = Service.executeQuery( query.toString() , [], [max:max,offset:offset]);
select
t1.ID,
t1.Name,
t2.Name as PARENT_Name
from SERVICE t1
left join SERVICE t2 on t1.PARENT_ID = t2.ID
order by t1.ID
最佳答案
问题是DomainClass.executeQuery()
执行HQL,HQL不支持自联接,并且在HQL中,您正在处理的是类而不是表,因此名称区分大小写。
自联接的等效项是相同类型的关联。例如,对于这样的Service
域类:
class Service {
String Name
Service parent
}
您可以像这样编写HQL查询:
select
t1.ID,
t1.Name,
t2.Name as PARENT_Name
from Service t1
left join Service.parent t2
order by t1.ID
在HQL中,将使用GORM /休眠关联创建联接。 HQL JOIN子句仅允许您更改关联类型:INNER,LEFT,RIGHT等。
关于hibernate - 使用Grails框架在Hibernate/Goram中加入SQL运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33147235/