Hibernate Criteria最近的收集日期字段

时间:2012-10-15 15:51:04

标签: java spring hibernate hibernate-criteria

我的实验室有一系列状态,这是我的简化课程:

    LabState {
        private Integer id;
        private State state;
        private Date date;
        private String comments;
    }

    State{
        private Integer id;
        private String name;

    }

    Lab{
        private Integer id;
        private List<LabState> states = new ArrayList<LabState>();
        private Date date;
        private String name
    }

我希望通过Hibernate Criteria获得特定实验室的最后状态。在mySql中,这工作正常:

SELECT ls.* FROM labs_states les INNER JOIN
    ( SELECT idLab, idLabState, MAX(date) AS lastDate FROM labs_states GROUP BY idLab)
        groupedLabs ON les.idLab = groupedLabs.idLab  AND les.date = groupedLabs.lastDate

编辑:SearchMethod:

   public List<Labs> search(LabSearch labSearch) {

            SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
            Session session = sessionFactory.openSession();

            Criteria criteria = session.createCriteria(Lab.class);

            criteria.add(Restrictions.like("name", "%" + labSearch.getName() + "%"));

            if(labSearch.getState() != null){
                criteria.createCriteria("states").add(Restrictions.eq("state", labSearch.getState())).addOrder(Order.asc("date")).list().get(0);


            return (List<Lab>) criteria.list();
}

我不知道如何使用Criteria执行此操作,或者是否有其他方法可以执行此操作

感谢

1 个答案:

答案 0 :(得分:1)

获取给定实验的最后状态

Criteria criteria = session.createCriteria(Lab.class)
    .add(Restrictions.like("name", "%" + labSearch.getName() + "%"));
    .createAlias("states", "labstate")
    .createAlias("labstate", "state")
    .addOrder(Order.desc("date"))
    .setProjection(Projections.list()
        .add(Projections.property("labstate.id"), "id")
        .add(Projections.property("labstate.date"), "date")
        .add(Projections.property("labstate.comments"), "comments")
        .add(Projections.property("state.name"), "state"))
    .setResultTransformer(Transformers.aliasToBean<LabstateDto>())
    .setMaxResults(1);

return (List<LabstateDto>)criteria.list();

如果你想要多个实验室返回其最后一个状态,你将需要另一个查询,这不是那么容易,因为你在db中有从Labstate到Lab ony的反向引用,而不是在类中。

更新:回复您的评论替代查询

Criteria criteria = session.createCriteria(Lab.class, "lab")
    .add(Restrictions.like("name", "%" + labSearch.getName() + "%"));
    .createAlias("states", "labstate")
    .add(Subqueries.proptertyEq("labstate.Id", DetachedCriteria.for(Lab.class)
        .add(Restrictions.propertyEq("id", "lab.id"));
        .createAlias("states", "lstate")
        .createAlias("labstate.state", "state")
        .add(Restrictions.eq("name", state));
        .addOrder(Order.desc("labstate.date"))
        .setProjection(Projection.property("labstate.Id"))
        .setMaxResults(1)
     );

return (List<Lab>)criteria.list();