我一直在尝试使用休眠计数行数,但我一直收到“0”记录。这里是我的代码使用休眠计数行或记录
public static Integer getLastDrugId(){
Integer result = 0;
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
String hql = "SELECT count(*) FROM Drug";
Query query = session.createQuery(hql);
Integer e = (Integer) query.iterate().next();
if (e != null) {
result = 1;
}
} catch (Exception ex) {
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
return result;
}
我在某处错了吗?
你检查,如果你得到一个异常?你可能应该添加一个记录器,让它在你的catch块中打印栈跟踪,不要错过它。 –
我在某种程度上是新的计数行。但是在打印stacktrace后,我得到了这个错误“java.lang.Long不能转换为java.lang.Integer”。但我并没有在我的代码中使用Long。 –
看起来像你的查询返回一个Long,所以你必须按照这样的方式接收它。如果需要将结果作为Integer,则可以通过在查询返回的Long上调用intValue()来手动进行转换。 –