ORMLite - return item w/ maximum ID (or value)

此生再无相见时 提交于 2019-12-30 07:09:08

问题


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.


回答1:


Your answer looks good @Ben but I thought I'd give some extra info for posterity:

  1. You could use a queryForFirst if you know your limit(1) will return a single result.

    qBuilder.orderby("my_field_column_name", false);
    qBuilder.limit(1L);
    MyEntity maxEntity = myEntityDao.queryForFirst(qBuilder.prepare());
    
  2. 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.




回答2:


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();


来源:https://stackoverflow.com/questions/8970221/ormlite-return-item-w-maximum-id-or-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!