我有这段代码
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
如何才能获得这个简单的记录计数???
答案 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);
}