【问题标题】:Query for last id in table查询表中的最后一个id
【发布时间】:2013-04-08 10:07:01
【问题描述】:

我需要获取表中最后一条记录的 ID。我试过了:

Dao<ParticipantModel,Integer> participantDao  = getHelper().getParticipantsDao();
        participant = participantDao.query(participantDao.queryBuilder()
                 .orderBy("id", false).prepare()).get(1);

我不确定如何使用QueryBuilder 来获得我正在寻找的结果。提前感谢您的任何想法。

【问题讨论】:

    标签: ormlite query-builder


    【解决方案1】:

    在我的应用程序中,我只需将 limit(int) 添加到准备好的查询中,如下所示:

    Dao<ParticipantModel,Integer> participantDao  = getHelper().getParticipantsDao();
        participant = participantDao.query(participantDao.queryBuilder()
             .orderBy("id", false).limit(1L).prepare());
    

    【讨论】:

      【解决方案2】:

      在请求中向 DBMS 询问 maxId 更有效。因为 DBMS 不应该对行进行排序。 this answer中有一个很好的例子

          QueryBuilder<MODEL, ID> qb = dao.queryBuilder().selectRaw("max(id)");
          String[] columns = new String[0];
          try {
              GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString());
              columns = results.getFirstResult();
          } catch (SQLException e) {
              e.printStackTrace();
          }
          if (columns.length == 0) {
              // NOTE: there are not any rows in table
              return 0;
          }
          return Integer.parseInt(columns[0]);
      

      【讨论】:

        【解决方案3】:

        你可以简单地使用它:

        ParticipantModel lastItem = participantDao.queryBuilder().orderBy("id", false).limit(1L).query().get(0);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-13
          • 1970-01-01
          • 2020-04-09
          • 1970-01-01
          相关资源
          最近更新 更多