一、获取记录总数问题
例子:
public Integer findRows(Comment entity) {
BigInteger result = BigInteger.ZERO;
StringBuilder sql = new StringBuilder();
sql.append(" SELECT COUNT(c.id) FROM ");
sql.append(" t_comment c ");
sql.append(" WHERE ");
sql.append(" c.belong_id=:belongId ");
sql.append(" AND c.belong_type=:belongType ");
logger.info("SQL:{}", sql.toString());
Query query = em.createNativeQuery(sql.toString(),Integer.class);
query.setParameter("belongId", entity.getBelongId());
query.setParameter("belongType", entity.getBelongType());
result = (BigInteger) query.getSingleResult();
return result.intValue();
}
异常:
javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown entity: java.lang.Integer
解决方法:
Query query = em.createNativeQuery(sql.toString(),Integer.class); ===>
Query query = em.createNativeQuery(sql.toString());
同时注意c.id的数据类型,我库里用的是BigInt,而且是原生SQL查询,所以自动映射成BigInteger,
如果是非原生SQL查询,可能映射成你在Entity定义的类型。