【问题标题】:How to get latest record from postgresql db?如何从 postgresql db 中获取最新记录?
【发布时间】:2016-09-01 14:05:53
【问题描述】:

我正在使用 Hibernate+ postgreql 数据库。我也使用 session 进行 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 查询?

【问题讨论】:

  • 提示:在普通 SQL 中,您正在寻找 ORDER BY lastupdated LIMIT 1
  • 你的模型中有 lastupdate 属性??
  • 是的@Mohamed Nabli

标签: hibernate postgresql


【解决方案1】:

试试这个例子:

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

【讨论】:

    【解决方案2】:

    我已经使用了以下方法。

               @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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2013-06-26
      相关资源
      最近更新 更多