我尝试使用java和hibernate来扩展一个小应用程序,当我运行此应用程序的测试类时,我收到此错误消息:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: insert into REUNION (TITREREUNION, DATEREUNION) values (?, ?)
Hibernate: insert into REUNION (TITREREUNION, DATEREUNION) values (?, ?)
Hibernate: insert into REUNION (TITREREUNION, DATEREUNION) values (?, ?)
Exception in thread "main" java.lang.ClassCastException: org.hibernate.impl.QueryImpl cannot be cast to javax.persistence.Query
at metier.MetierImpl.getAllReunion(MetierImpl.java:62)
at Test.main(Test.java:21)
如您所见,错误是MetierImpl类:导致错误的方法是:
public Reunion getAllReunion(){
Session session =sessionFactory.getCurrentSession();
session.beginTransaction();
Query req=(Query) session.createQuery("select R from Reunion ");
List<Reunion> list = req.getResultList();
Reunion r=(Reunion) req.getResultList().get(0);
return r;
}
答案 0 :(得分:3)
Hibernate Session.createQuery()返回org.hibernate.Query
的实例。您的代码将此对象强制转换为javax.persistence.Query
,但它不是javax.persistence.Query
的实例。所以你得到了这个例外。
不要进行此转换,并导入正确的Query类:不是javax.persistence.Query
,而是org.hibernate.Query
。