Hibernate嵌套查询

时间:2013-03-13 06:11:42

标签: java hibernate spring-mvc hql

我们正在尝试为下面创建特定于hibernate的查询 lSession.createQuery(lQueryString.toString()); ............

INSERT INTO EMPLOYEE_HISTORY (emp_status,
                              createdBy,
                              releasedate,
                              year)
   SELECT CASE n.emp_Status WHEN 0 THEN 'Draft' ELSE 'Final' END,
          m.createdBy,
          m.releasedate,
          m.year
     FROM EMPLOYEE m, (SELECT COUNT (1) EMPLOYEE_HISTORY   b,EMPLOYEE a where a.emplid=b.emplid and a.year=b.year and b.year=2012 and a.doc_id='XYZ') n 
     where a.doc_id='xyz'

getting following exception,I guess it because of below statement in query
(SELECT COUNT (1) EMPLOYEE_HISTORY   b,EMPLOYEE a where a.emplid=b.emplid and a.year=b.year and b.year=2012 and a.doc_id='XYZ') n


org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 374 
INSERT INTO EMPLOYEE_HISTORY (emp_status,
                              createdBy,
                              releasedate,
                              year)
   SELECT CASE n.emp_Status WHEN 0 THEN 'Draft' ELSE 'Final' END,
          m.createdBy,
          m.releasedate,
          m.year
     FROM EMPLOYEE m, (SELECT COUNT (1) EMPLOYEE_HISTORY   b,EMPLOYEE a where a.emplid=b.emplid and a.year=b.year and b.year=2012 and a.doc_id='XYZ') n 
     where a.doc_id='xyz'

例外

at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
    at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
    at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
    at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
    at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
    at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
    at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
    at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
    at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
    at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)

如果有任何建议/输入,请提供。

1 个答案:

答案 0 :(得分:1)

看起来像是将SQL而不是HQL传递给Session.createQuery(...)方法。

请参阅:http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-querying-executing

例如:

INSERT INTO EMPLOYEE_HISTORY (...)

'EMPLOYEE_HISTORY'应该是实体类名称(如EmployeeHistory)而不是表名。

同样在HQL中,您可以使用实体中定义的引用来完成关联,避免通过ID进行隐式连接,就像您在此处一样

where a.emplid=b.emplid and ...

考虑以上网址的示例:

select mother from Cat as cat join cat.mother as mother where cat.name = ?