objectbox-java icon indicating copy to clipboard operation
objectbox-java copied to clipboard

How to get the latest record of each item?

Open JimmyTheNerd opened this issue 8 years ago • 6 comments

Hi there,

I'd like to select all latest record of each item, which is possible with GreenDAO, but I couldn't find an equivalent for ObjectBox yet.

Pseudocode:

List<MyItem> latestByName = box.query()
.orderDesc(MyItem_.creationDate)
.groupBy(MyItem._name)
.build()
.find();

The following resources unfortunately didn't solve the issue:

  1. https://github.com/objectbox/objectbox-java/issues/198
  2. http://objectbox.io/objectbox-1-4-property-queries-entity-inheritance/
  3. https://github.com/objectbox/objectbox-java/issues/422#issuecomment-379745214

Does anyone know a solution? Thank you!

JimmyTheNerd avatar Oct 22 '18 15:10 JimmyTheNerd

find() will return you all items then you can just select the last item in the list?

items = query.find()
items.get(items.size -1)

abdurahmanadilovic avatar Oct 24 '18 10:10 abdurahmanadilovic

find() will return you all items then you can just select the last item in the list?

items = query.find()
items.get(items.size -1)

Thanks for your reply, but that's not what I'm looking for. I need the latest item of each, not the latest item.

Something like SELECT ... FROM ... WHERE ... ORDER BY creationDate DESC GROUP BY itemId.

Any idea?

JimmyTheNerd avatar Oct 24 '18 14:10 JimmyTheNerd

ObjectBox is not based on rows and columns and thus has no "group by". Doesn't make much sense for objects.

You can first for distinct property values, and then do a regular query for each of those values. Let us know if you need additional help on that.

greenrobot avatar Oct 25 '18 10:10 greenrobot

Closing this issue due to inactivity. :zzz: Please re-open with more details or submit a new issue. -ut

greenrobot-team avatar Nov 06 '18 09:11 greenrobot-team

@JimmyTheNerd did not you find any solution for this?

HasanHaghniya avatar Oct 23 '21 10:10 HasanHaghniya

find() will return you all items then you can just select the last item in the list?

items = query.find()
items.get(items.size -1)

Thanks for your reply, but that's not what I'm looking for. I need the latest item of each, not the latest item.

Something like SELECT ... FROM ... WHERE ... ORDER BY creationDate DESC GROUP BY itemId.

Any idea?

I agree that find() is not good as it dumps all the records, but didn't find an off-the-shelf method. I end up with the code below (Kotlin)

box.query().build().find(box.count() - 1, 1).last()

freddie1129 avatar Nov 09 '22 01:11 freddie1129