How to get the entity with the newest date
Asked Answered
S

3

5

Does anyone have any idea how to retrieve the last(with the newest date) entity in objectify? I know how to make a query but how to retrieve the one with the newest date?

List<Transaction> fetched2 = ofy.query(Transaction.class).filter("someproperty", somepropertyvalue).order("date").list();

I could try to bubble sort it but I´m sure there is an easier way. THX

Socialistic answered 16/5, 2012 at 13:42 Comment(1)
something like adding .get(0) ?Mcelrath
M
8

You just have to add a minus in front of "date" in your order :

List<Transaction> fetched2 = ofy.query(Transaction.class).filter("someproperty", somepropertyvalue).order("-date").list();

That should return you a list of Transaction with the newest one in first position.

Mahla answered 16/5, 2012 at 14:1 Comment(3)
thank you for answering, but I already know that, probably I wasnt clear enough. I want to get this entity (the 1st or last depending on sorting) out of the list.Socialistic
I would say, as you are in a list, a simple fetched2.get(0), or fetched2.get(fetched2.size() -1) would work... as the list is already sorted, this will return the newest and oldest Transaction.Mahla
The easiest way is then : Transaction tr = ofy.query(Transaction.class).filter("someproperty", somepropertyvalue).order("-date").get(); This should only return the last added item.Mahla
T
0

I don't know about your use case, but if you are tying to get "new" entities (ones added/updated after the last query) you might want to use Cursors. They are much more efficient as they only get new/updated entities: https://developers.google.com/appengine/docs/java/datastore/queries#Query_Cursors

Tomikotomkiel answered 16/5, 2012 at 18:41 Comment(0)
M
0

if you want to perform sorting in objectify you should user order by method. For example if you have a table Sample and you want to apply sorting on it

Ascending sorting Sample sample = ofy.query(Sample .class).filter("propertyname", "propertyvalue).order("+date").list().first();

gets the first record in the

Descending sorting Sample sample = ofy.query(Sample .class).filter("propertyname", "propertyvalue).order("+date")

Maclay answered 7/7, 2014 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.