MySQL查询Hibernate Criteria

时间:2016-11-08 07:00:16

标签: mysql hibernate hibernate-criteria

我有一个包含idseq_idtran_date列的表格。

示例数据:

id     | seq_id | tran_date
------ | ------   --------
1      |  1     |  2016-11-01
1      |  2     |  2016-11-01
1      |  1     |  2016-11-02
1      |  2     |  2016-11-02
1      |  1     |  2016-11-12
1      |  2     |  2016-11-12

我的预期结果是

1      |  2     |  2016-11-02

条件

tran_date应该小于今天(2016-11-08)并且应该列出max(seq_id)记录。

如何使用上面的标准api实现Hibernate查询?

现在使用的实时MySQL查询如下,需要将其转换为Hibernate Criteria:

SELECT *
  FROM testtable tt 
  WHERE CONCAT(DATE_FORMAT(tt.tran_date, '%Y%m%d'), LPAD(tt.seq_id , 2, '0')) =
    (SELECT MAX(CONCAT(DATE_FORMAT(mtv1.tran_date, '%Y%m%d'), LPAD(mtv1.seq_id , 2, '0')))
    FROM testtable tt1 WHERE tt1.`Label_Id` = tt1.`id` 
    AND mtv1.tran_date<= CURRENT_DATE() GROUP BY mtv.`id`) 

1 个答案:

答案 0 :(得分:0)

您可以使用Hibernate Criteria等效的SQL查询。

public YourClassName getResult() throws ParseException {
    Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2016-11-08");
    Criteria criteria = session.createCriteria(YourClassName.class);
    criteria.add(Restrictions.lt("tran_date", date));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.max("id"), "id");
    projectionList.add(Projections.max("seq_id"), "seq_id");
    projectionList.add(Projections.max("tran_date"), "tran_date");
    criteria.setProjection(projectionList);
    criteria.setResultTransformer(new AliasToBeanResultTransformer(YourClassName.class));
    if (criteria.list().isEmpty()) {
        return null;
    } else {
        YourClassName yourClassName = (YourClassName) criteria.list().get(0);
        return yourClassName;
    }
}