hibernate连接多个表和组条件

时间:2013-03-22 19:53:15

标签: hibernate hql criteria

我有四个表,如下所示。我想通过加入所有这4个表来查询并检索电子邮件,注册日期,上次访问日期,没有访问次数,并且没有提供反馈,也没有上传文件。

Class User{
     int userId;
     String email;
     Date registeredDate;
     UserVisits userVisits; //one-to-one relation
     Set<UserFeedback> feedbacks; //one-to-many
     Set<UserUploads> uploads // one-to-many
}

Class UserVisits{
     int userId;
     Date lastVisited;
     int noOfVisits;
}

Class UserFeedback{
     int feedbackId;
     int userId;
     String feedback;
     Date feedbackDate
}

Class UserUploads{
      int fileId;
      User user;
      int fileName;
 }

任何人都可以帮助我如何实现这一目标。

先谢谢。

SREE

修改 我的sql看起来像

select this_.email as email, this_.created_date as created_date,
userlogins1_.last_login as last_login, userlogins1_.login_count as login_count, 
fb_count, upload_count from user_details this_ 
left outer join user_logins userlogins1_ on this_.user_id=userlogins1_.user_id 
left outer join (select count(feedback_id) as fb_count, user_id 
from user_feedback group by user_id) as uf on this_.user_id=uf.user_id
left outer join (select count(uploadid) as upload_count, user_id 
from user_uploads group by user_id) as m on this_.user_id=m.user_id
order by this_.email asc

我如何使用这样的多个子查询?

更新。有解决方案但有问题

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class, "user");
criteria.createAlias("user.userLogins","userLogins",Criteria.LEFT_JOIN);

DetachedCriteria fbCriteria = DetachedCriteria.forClass(UserFeedback.class, "feedback");
fbCriteria.add(Restrictions.eqProperty("feedback.userId", "user.userId"));
fbCriteria.setProjection(Projections.alias(Projections.count("feedback.userId"), "fbcount"));
fbCriteria.addOrder(Order.asc("fbcount"));
criteria.add(Subqueries.exists(fbCriteria)); 

DetachedCriteria mapCriteria = DetachedCriteria.forClass(FileUploads.class, "uploads");
mapCriteria.add(Restrictions.eqProperty("uploads.user.userId", "user.userId"));
mapCriteria.setProjection(Projections.count("uploads.user.userId"));
criteria.add(Subqueries.exists(mapCriteria)); 

List<User> users = criteria.list();

这将返回我正在寻找的内容。对于带有“fbcount”“0”的行,我希望在asc中排序时首先出现。但它正在发生。 “fbcount”值“0”的行始终位于末尾。

请有人建议我如何实现这一目标。

0 个答案:

没有答案