Query for last id in table
Asked Answered
O

3

5

I need to get the id of the last record in my table. I have tried:

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

I'm not sure of how to use the QueryBuilder to get the result I'm looking for. Thanks in advance for any ideas.

Orestes answered 8/4, 2013 at 10:7 Comment(0)
O
8

In my application I do the same just add the limit(int) to prepared query like this:

Dao<ParticipantModel,Integer> participantDao  = getHelper().getParticipantsDao();
    participant = participantDao.query(participantDao.queryBuilder()
         .orderBy("id", false).limit(1L).prepare());
Osteitis answered 8/4, 2013 at 10:42 Comment(0)
P
1

It is more efficient to ask DBMS for maxId in request. Cause DBMS shouldn't perform sorting of rows. There is a good example in 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]);
Pteranodon answered 14/1, 2015 at 18:38 Comment(0)
S
1

You can use this simply:

ParticipantModel lastItem = participantDao.queryBuilder().orderBy("id", false).limit(1L).query().get(0);
Supranational answered 6/5, 2018 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.