使用Hibernate进行数据库查询时出现语法错误

时间:2018-02-01 10:10:28

标签: java sql hibernate hql

我有以下查询。当我执行它时,我得到了这样的错误:

[http-nio-8090-exec-9] WARN  org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42601
[http-nio-8090-exec-9] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: syntax error at or near "."
  Position: 5385

我认为问题出在select CG.codes from CodeGroup CG,但如何正确编写此查询?我需要获取属于codes的所有CodeGroupcodesCode的列表。

    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("select distinct AI from AppInfo AI ")
            .append("left join fetch AI.plan as PSAP ")
            .append("where PSAP.edType in ( select C from Code C where C.column1= 'XXXX' ")
            .append("and C in (select CG.codes from CodeGroup CG where CG.name = 'YYYY'))");

2 个答案:

答案 0 :(得分:1)

您的第left join fetch AI.plan as PSAP行错了。省略fetch

答案 1 :(得分:0)

我观察到的是,您的选择查询存在小问题,应该是这样的

StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("select DISTINCT AI.COLUMN_NAME from AppInfo AI ")
            .append("left join fetch AI.plan as PSAP ")
            .append("where PSAP.edType in ( select C from Code C where C.column1= 'XXXX' ")
            .append("and C in (select CG.codes from CodeGroup CG where CG.name = 'YYYY'))");

因为,AI是AppInfo表的别名。 Distinct适用于特定列。