ORMLite - return item w/ maximum ID (or value)
Question
I'm using ORMLite w/ Android. I want to grab the ID value of the object w/ the highest-valued ID.
I'd also like to generalize this to requesting a single object w/ max/min value for any arbitrary field. What is the best practice for doing this?
I realize I could execute a raw query, but is there any other way that jumps out at anyone? I'm imagining something similar to Predicates when executing FetchRequests in CoreData on iOS.
Solution
Your answer looks good @Ben but I thought I'd give some extra info for posterity:
You could use a
queryForFirst
if you know yourlimit(1)
will return a single result.qBuilder.orderby("my_field_column_name", false); qBuilder.limit(1L); MyEntity maxEntity = myEntityDao.queryForFirst(qBuilder.prepare());
A raw query would also work. It involves more objects and checking but will be cheaper if the table size is large since you don't need to do the ordering.
qBuilder.selectRaw("MAX(my_field_column_name)"); GenericRawResults<String[]> results = myEntityDao.queryRaw(qBuilder.prepareStatementString()); String[] result = results.getResults().next(); int max = Integer.parseInt(result[0]);
Obviously, if your column was a different type then you would get a different object out of result[0]
that you would have to convert into the appropriate type depending on the object.
OTHER TIPS
Ahh, upon further review of the ORMLite documentation, it appears I want something like this:
QueryBuilder<MyEntity,ItsIdType> qBuilder = myEntityDao.queryBuilder();
qBuilder.orderby("my_field_column_name",false); // false for descending order
qBuilder.limit(1);
List<MyEntity> listOfOne = qBuilder.query();