我正在尝试使用Java 8,Spring和Hibernate在项目中将方法传递给控制器。但是我遇到“请求处理失败;嵌套异常为java.lang.ClassCastException:无法将java.lang.Long强制转换为java.lang.Integer”的错误。
我从KomitentDAO获得的方法如下
@Override
public int vratiBroj() {
Session currentSession = sessionFactory.getCurrentSession();
int num = 0;
Query query = currentSession.createQuery("SELECT count(*) from
Komitent");
num = (int) query.getSingleResult();
return num;
}
并且控制器喜欢这样
@GetMapping("/dodaj")
public String prikaziForm(Model theModel) {
Komitent komt = new Komitent();
int a = komitentService.vratiBroj();
komt.setSifra(a);
theModel.addAttribute("komitent", komt);
return "komitent-form";
}
我需要在我的函数中的komt.Sifra中设置一个整数。该查询只是一个测试,可以是其他任何返回单个int的查询。我在做什么错,有没有更好的方法来查询数据库并将值返回给Model?
答案 0 :(得分:0)
count(*)确实返回Long而不是Integer。
因此您的方法应类似于:
public int vratiBroj() {
Session currentSession = sessionFactory.getCurrentSession();
Query query = currentSession.createQuery("SELECT count(*) from Komitent");
long num = (Long) query.getSingleResult();
return num.intValue();
}