Hibernate5:如何让Root <long>进行记录计数查询?

时间:2017-09-03 23:26:59

标签: java hibernate hibernate-criteria

我有这段代码

final Session session = sessionFactory.getCurrentSession();
final CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
final CriteriaQuery<ListingDetailBaseDto> criteria = builder.createQuery(ListingDetailBaseDto.class);
final Root<ListingDetailBaseDto> root = criteria.from(ListingDetailBaseDto.class);

...

public int countRecords() {
    final CriteriaQuery<Long> countingQuery = builder.createQuery(Long.class);
    countingQuery.select(countingQuery.from(Long.class));
    countingQuery.select(builder.count(root));
    final Query<Long> query = session.createQuery(countingQuery);
    return query.getSingleResult().intValue();
}       

它说Long不是一个有效的实体。所以我删除第3行,

public int countRecords() {
    final CriteriaQuery<Long> countingQuery = builder.createQuery(Long.class);
    countingQuery.select(builder.count(root));
    final Query<Long> query = session.createQuery(countingQuery);
    return query.getSingleResult().intValue();
}   

然后错误变为:No criteria query roots were specified

如何才能获得这个简单的记录计数???

2 个答案:

答案 0 :(得分:0)

感谢@ O.Badr询问root,这让我更加关注代码的这一部分。

问题是由于使用来自其他root对象的CriteriaQuery造成的。

固定代码:

public int countRecords() {
    final CriteriaQuery<Long> countingQuery = builder.createQuery(Long.class);
    countingQuery.select(builder.count(countingQuery.from(ListingDetailBaseDto.class)));
    final Query<Long> query = session.createQuery(countingQuery);
    return query.getSingleResult().intValue();
}       

答案 1 :(得分:0)

稍微偏离主题,但我们放弃了休眠,这么好的imo。

class ListingDetailsDao extends JdbcDaoSupport {

    public ListingDetailsDao (@Autowired @Qualifier("myDataSource") DataSource dataSource) {

        setDataSource(dataSource);
    }

    public int count() {

        final String sql = "select count (*) from listing_details";
        return getJdbcTemplate().queryForObject(sql, Integer.class);
    }