2016-05-06 68 views
1

我正在使用Hibernate + postgreql數據庫。我也使用過會話進行CRUD操作。我完成了插入操作的成功。我需要知道如何從實體獲取最新記錄。如何從postgresql db獲取最新記錄?

@Repository 
@Transactional 
public class IncidentsDAOImpl extends BaseDAO implements IncidentsDAO{ 
@Override 
public Incidents getLatestRecord(String roleId) { 
Incidents obj=new Incidents(); 
List<Incidents> incidents = null; 
incidents = (List<Incidents >) getSession() 
       .createCriteria(Incidents .class) 
       .add(Restrictions.eq("roleId", roleId)) 
       .add(<how to add lastupdate query---------------------->); 
    obj=(incidents != null && !incidents .isEmpty()) ? incidents 
       .get(0) : null; 
    return obj; 
} 

如何添加lastupdate查詢?

+0

提示:在純SQL中,您正在尋找'ORDER BY lastupdated LIMIT 1'。 –

+0

你有你的模型中的lastupdate屬性? –

+0

是@Mohamed Nabli – user5863037

回答

0

嘗試這個例子:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); 
    String myDate = "17-04-2011"; 
    // Create date 17-04-2011 - 00h00 
    Date minDate = formatter.parse(myDate); 
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class 
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1)); 
    Conjunction and = Restrictions.conjunction(); 
    // The order date must be >= 17-04-2011 - 00h00 
    and.add(Restrictions.ge("orderDate", minDate)); 
    // And the order date must be < 18-04-2011 - 00h00 
    and.add(Restrictions.lt("orderDate", maxDate)); 

來源:Hibernate Criteria for Dates

0

我曾嘗試使用下面的方法來完成。

  @Repository 
      @Transactional 
      public class IncidentsDAOImpl extends BaseDAO implements IncidentsDAO{ 
      @Override 
      public Incidents getLatestRecord(String roleId) { 
      List<Incidents> obj=new ArrayList<Incidents>(); 
      try{ 
      Criteria criteria = getSession() 
      .createCriteria(Incidents.class) 
      .add(Restrictions.eq("roleId", roleId)) 
      .addOrder(Order.desc("lastUpdatedOn")); 
      obj=criteria.list(); 

     } catch (Exception ex) { 
     throw ex; 
    } 
return (obj!= null && !obj.isEmpty()) ? obj.get(0): null; 
}