我正在尝试使用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?
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句