如何从postgresql db获取最新记录?

时间:2016-05-06 13:14:20

标签: hibernate postgresql

我正在使用Hibernate + postgreql数据库。我也使用了会话进行CRUD操作。我成功完成了插入操作。我需要知道如何从实体获取最新记录。

 @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查询?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
}