我正在尝试使用HQL
查询打印已获取数据的详细信息,如下所示
List list = sess.createQuery("from PostMessages as pm "
+ " left join pm.postImageses as pi "
+ " left join pm.videosDescriptions as vd "
+ "where pm.messageid=:msgId")
.setParameter("msgId", msgId).list();
List<PostMessages> result = (List<PostMessages>) list;
Iterator itr = result.iterator();
while (itr.hasNext()) {
PostMessages pm = (PostMessages) itr.next();
System.out.print("msg: " + pm.getMessage());
System.out.print(" type: " + pm.getMessageType());
Set images = pm.getPostImageses();
Iterator itr1 = images.iterator();
while (itr1.hasNext()) {
PostImages pi = (PostImages) itr1.next();
System.out.print("id: " + pi.getImageId());
System.out.print("desc: " + pi.getImgDesc());
}
Set videos = pm.getVideosDescriptions();
Iterator itr2 = videos.iterator();
while (itr2.hasNext()) {
VideosDescription vd = (VideosDescription) itr1.next();
System.out.print("id: " + vd.getVideoId());
System.out.print("desc: " + vd.getDescription());
}
}
但这显示以下异常
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
hibernetMappings.PostMessages
at hibernetMappings.TestPost.main(TestPost.java:40)
如何解决此异常。
答案 0 :(得分:1)
在查询中添加一个select子句:
select distinct pm from PostMessages as pm ...
请注意,左连接没用。如果目标是在单个查询中检索包含其图片和视频说明的帖子消息,则应使用left join fetch
。
您还应该使用Iterator<PostMessages>
,而不是原始迭代器。实体应该命名为PostMessage
,而不是PostMessages
:每个实例都是一条消息,而不是几条消息。 getImageses()
应为getImages()
。
答案 1 :(得分:-1)
尝试这样做。
Iterator itr = result.iterator();
到
Iterator<PostMessages> itr = result.iterator();
同时更改
List<PostMessages> list = sess.createQuery("from PostMessages as pm "
+ " left join fetch pm.postImageses as pi "
+ " left join fetch pm.videosDescriptions as vd "
+ "where pm.messageid=:msgId")
.setParameter("msgId", msgId).list();