我需要使用Criteria
将此SQL表达式
转换为Hibernate
select id,field1,field2,count(*) from my_table
group by field1,field2 having count(*)>1;
这是到目前为止我的代码。
final Session session = ......
ProjectionList projectionList = (ProjectionList)emptyProjection();
projectionList.add(Projections.property("id"),"id");
projectionList.add(Projections.groupProperty("codeI"));
projectionList.add(Projections.groupProperty("codeII"));
projectionList.add(Projections.sqlGroupProjection("count(*)","having count(*)>1",new String[]{},new Type[]{StandardBasicTypes.INTEGER}));
final Criteria criteria = session.createCriteria(MyClass.class).setProjection(projectionList).setResultTransformer(transformer(MyClass.class));
return new ArrayList<MyClass>(criteria.list());
我的问题是
标准正在生成此 SQL。
group by
this_.FIELD1,
this_.FIELD2,
having
count(*)>1
如您所见,第二组后面跟着一个 COMMA
this_.FIELD2,
并且 mySQL 抛出 SyntaxError
更新
这是我的 hibernate.cfg
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
我们使用的是 mysql 5.5.29
和 HIBERNATE 4.2.3
希望有人给点建议。
最诚挚的问候..
最佳答案
Hibernate 不支持 Criteria API 中的 having 子句。您的代码非常接近您想要的 SQL,但您实际指定的只是另一个 group by 条件,因此需要逗号。这是很久以前的一个功能请求:https://hibernate.atlassian.net/browse/HHH-1043 。
如果您必须使用条件,那么您可以使用子查询,但这最终会很慢。 HQL 确实支持该子句,因此您可以这样做。
更多讨论和示例:Hibernate Criteria API - HAVING clause work arounds .
关于Java Hibernate sqlGroupProjection mysql 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186828/