【问题标题】:MSSQL Issue Hibernate CriteriaMSSQL 问题休眠标准
【发布时间】:2018-05-08 11:44:13
【问题描述】:

我正在使用带有两个数据库(Postgresql 和 MSSQL)的 Java-Hibernate。 SqlServer2012 带方言:

hibernate.dialect = org.hibernate.dialect.SQLServer2012Dialect

我写了一个标准查询,例如:

DetachedCriteria detachedCriteria=DetachedCriteria.forClass(entityClazz);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max(COMPOSEDID_VERSION_ID));
proj.add(Projections.groupProperty(COMPOSEDID_ID));
detachedCriteria.setProjection(proj);

criteria = session.createCriteria(entityClazz)
            .add( Subqueries.propertiesIn(new String[] { COMPOSEDID_VERSION_ID, COMPOSEDID_ID }, detachedCriteria));

此查询在 Postgre Db 中运行良好。但是当我切换到 MSSQL 时,出现以下错误:

Caused by: java.sql.SQLException: An expression of non-boolean type specified in a context where a condition is expected, near ','.
    at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
    at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
    at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
    at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
    at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
    at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:1029)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)[201:org.hibernate.core:5.0.0.Final] 

谁能帮帮我?我应该在 Criteria API 中进行哪些更改以实现针对每个 Id 获取 maxVersion 记录的目标??

【问题讨论】:

标签: sql-server hibernate hibernate-criteria


【解决方案1】:

不要在分离标准的投影标准中添加子查询,而是直接在标准中添加投影,如下所示:

DetachedCriteria detachedCriteria=DetachedCriteria.forClass(entityClazz);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max(COMPOSEDID_VERSION_ID));
proj.add(Projections.groupProperty(COMPOSEDID_ID));


criteria = session.createCriteria(entityClazz)
.setProjection( proj );

【讨论】:

  • 这种方法适用于简单的直接查询,我试图为 MSSQL 不支持的多个列的 WHERE-IN 子句实现它。
猜你喜欢
  • 2011-08-13
  • 2011-05-07
  • 1970-01-01
  • 2011-10-09
  • 2012-12-24
相关资源
最近更新 更多