【问题标题】:org.hibernate.Criteria not working properly with Projections.rowCount()org.hibernate.Criteria 不能与 Projections.rowCount() 一起正常工作
【发布时间】:2013-05-23 13:45:24
【问题描述】:

在我的应用程序的某个时间点,我进行计数以显示数据表的总记录 - 在这种情况下按服务计算合同的计数 - 如下所示:

public int countByServices(ContractFilter filter) {
        Criteria criteria = ((Session) entityManager.getDelegate()).createCriteria(ContractServiceDB.class);
        criteria.createAlias("contract", "contract", Criteria.INNER_JOIN);
        criteria.add(Restrictions.eq("contract.status", filter.getStatus().getId()));
        criteria.add(Restrictions.isNull("contract.processed"));
        criteria.add(Restrictions.eq("contract.customerId", filter.getCustomerId()));
        criteria.add(Restrictions.in("service", filter.getServices()));
        criteria.setProjection(Projections.rowCount());
        return ((Long) criteria.uniqueResult()).intValue();
}

Contract 和 Service 是多对多的关系,ContractServiceDB 是链接实体,因为它有自己的属性。查询第一次运行良好,但是当稍后再次调用该方法时,它会引发异常:

org.hibernate.PropertyAccessException: could not get a field value by reflection getter of br.com.foo.bar.db.entity.ContractServiceDBPK.cdSncode
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field br.com.foo.bar.db.entity.ContractServiceDBPK.cdSncode to java.lang.Long

cdSncode 是实体的主键之一,因为它是嵌入的。当然,我声明了它的 getter:

public String getCdSncode() {
        return this.cdSncode;
}

String 到 Long 的转换线是 countByServices 方法的返回 - 奇怪的是,结果不再是 Long 值,即使投影设置为 rowCount。我也试过了

criteria.setProjection(Projections.countDistinct("contract"));

这给了我同样的例外。

我做错了什么?如有必要,我可以为您提供更多代码。感谢您的帮助。

【问题讨论】:

  • 如果同样的事情一次有效,但后来又失败了,我们可以从检查这两次之间的变化开始。在这种情况下发生了什么变化?
  • 我今天遇到了同样的问题。如果我在没有限制的条件下调用 rowCount(),它工作正常。当我有限制地调用它时,就会发生异常......如果你找到了解决方案,请分享!

标签: hibernate count criteria hibernate-criteria


【解决方案1】:

我遇到了类似的问题。

看起来你正在以错误的方式执行标准:

criteria.add(Restrictions.eq("contract.status", filter.getStatus().getId()));

您必须改为使用“contract.status.id”。

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2014-07-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多