Last Record of one to many relation Hibernate Crit

2019-08-13 22:45发布

问题:

I need to get last record and the main record of one-to-many relation with Hibernate criteria. The Pseudo-Sql show the query I want to execute

Table1(Master)
Table2(Details)

Select *  
      from Table1 tab1, Table2  tab2 
              where tab2.tab1id == tab1.id 
              and tab2.date == (  select Max(date) 
                                    from table2 where table2.tab1id == tab1.id)

回答1:

I did it!!!

DetachedCriteria maxFecha = DetachedCriteria
.forClass(CambiosEstado.class, "cambio")
.setProjection(Projections.max("fecha"))
.add(Property.forName("cambio.practicasEst").eqProperty("cambio2.practicasEst"));  
Criteria criteria = this.getSession().createCriteria(
PracticasEst.class);
Criteria estadosCriteria = criteria.createCriteria(
"cambiosEstados", "cambio2");
estadosCriteria.add(Restrictions.eq("estados", estados));
estadosCriteria.add(Property.forName("fecha").eq(maxFecha));
return criteria.list();

the Master Class is PracticasEst that has a collection of CambiosEstado. the query take the PracticaEst and the last CambiosEstado. (Fecha is Date in spanish).