嗨请在下面的表和查询。这取自别人的帖子,但它完全按照我的需要。 我想创建Hibernate Criteria(No HQL或SQL),它产生的结果与此表下面的sql相同。
知道怎么做吗?
这是我尝试但不正确的方法。
criteria.setProjection(
Projections.projectionList()
.add(Projections.property("train"))
.add(Projections.max("time"))
.add(Property.forName("train").group())
);
TrainTable
Train Dest Time
1 HK 10:00
1 SH 12:00
1 SZ 14:00
2 HK 13:00
2 SH 09:00
2 SZ 07:00
SQL
SELECT t.Train, t.Dest, r.MaxTime
FROM (
SELECT Train, MAX(Time) as MaxTime
FROM TrainTable
GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime
结果
Train Dest Time
1 SZ 14:00
2 HK 13:00
答案 0 :(得分:0)
使用nativequery直接运行MySQL查询。这是最简单,最好的方式。请试试这个:
@Autowired
private SessionFactory mySessionFactory;
String query ="SELECT t.Train, t.Dest, r.MaxTime "
+" FROM (SELECT Train, MAX(Time) as MaxTime FROM TrainTable GROUP BY Train) r "
+" INNER JOIN TrainTable t "
+" ON t.Train = r.Train AND t.Time = r.MaxTime";
List<Object[]> list = (List<Object[]>) mySessionFactory.getCurrentSession().createNativeQuery(query)
.getResultList();
答案 1 :(得分:0)
鉴于我不知道模型和他们的关系,我认为这样的事情将指导你:
Criteria cr = session.createCriteria(R.class)
.setProjection(Projections.projectionList()
.add(Projections.property("train"), "train")
.add(Projections.property("dest"), "dest"))
.add( Projections.groupProperty("train"), "train" )
.createCriteria("trainTable").add(Projections.max("maxTime"))
.setResultTransformer(Transformers.aliasToBean(R.class));
List<R> list = cr.list();
有关详细信息,请尝试在this tutorial和this one too
进行研究