简体   繁体   中英

Last Record of one to many relation Hibernate Criteria

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)

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM