使用hibernate进行类强制转换异常

时间:2016-07-13 06:33:48

标签: java hibernate

我只是想检索数据列表,但是使用下面的代码为什么我会得到类转换异常......

public List<TbDiscussionForumAnswere> findTbDiscussionForumAnswerebyforumQuestionId(Integer forumQuestionId) {
session = sessionFactory.getCurrentSession();
TbDiscussionForumAnswere TbDiscussionForumAnswere = (TbDiscussionForumAnswere)session.createCriteria(TbDiscussionForumAnswere.class)                .add(Restrictions.eq("forumQuestionId.forumQuestionId", forumQuestionId));
return (List<TbDiscussionForumAnswere>) TbDiscussionForumAnswere.getTbDiscussionForumAnswereCollection();
}

上面的方法给我以下异常

java.lang.ClassCastException: org.hibernate.internal.CriteriaImpl cannot be cast to com.medikm.entity.TbDiscussionForumAnswere

谢谢你

3 个答案:

答案 0 :(得分:1)

您正在创建Criteria对象而不是TbDiscussionForumAnswere对象。这是一个正确的错误消息。 您使用此Criteria类来执行查询。你应该把它投到Criteria

答案 1 :(得分:1)

session.createCriteria(TbDiscussionForumAnswere.class).add(Restrictions.eq("forumQuestionId.forumQuestionId", forumQuestionId));返回Critera not和object TbDiscussionForumAnswere

因此您必须将行更改为:

Critera critera  = (Critera)session.createCriteria(TbDiscussionForumAnswere.class).add(Restrictions.eq("forumQuestionId.forumQuestionId", forumQuestionId));

答案 2 :(得分:0)

在我使用的代码下面,这对我来说很好,谢谢大家的答案

List<TbDiscussionForumAnswere> tbDiscussionForumAnswereList = session.createCriteria(TbDiscussionForumAnswere.class)
.add(Restrictions.eq("forumQuestionId.forumQuestionId",forumQuestionId))
.setFetchMode("forumQuestionId", FetchMode.LAZY)
.list();