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.
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment.
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());
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]);
You can use this simply:
ParticipantModel lastItem = participantDao.queryBuilder().orderBy("id", false).limit(1L).query().get(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With