Abstract Query: How to get latest record

Interesting pieces of code and stories
Post Reply
User avatar
Klaudiusz
Site Admin
Posts: 29
Joined: Tue Aug 07, 2018 9:55 pm
Contact:

Abstract Query: How to get latest record

Post by Klaudiusz » Tue May 07, 2019 10:45 am

Daobab FullORM gives you an oportunity to create abstract queries and methods.
Let's create a universal method to get latest record.

We want to akcept only tables with column InsertDate and PrimaryKey.
We want to get a table on input and return latest record or null:

Code: Select all

    public <E extends Entity & InsertDate & PrimaryKey> E getLatest(E table){
        return Select.one(db,table).orderDescBy(table.colInsertDate()).result();
    }


And usage of this method is very simple:

Code: Select all

    public void testLatest(){
        App latestApp=getLatest(tabApp);
        User latestUser=getLatest(tabUser);
        Role latestRole=getLatest(tabRole);
    }

Java won't let you give a table without primary key and insert date.

But what if we have different column names in tables? Should we have multiple queries?
Definatelly not.
In this case just modify our method like this:

Code: Select all

    public <C extends Column<E, Timestamp,?>,E extends Entity & PrimaryKey> E getLatest(C dateColumn){
        return Select.one(db,dateColumn.getThisEntity()).orderDescBy(dateColumn).result();
    }
Usage:

Code: Select all

    public void testLatest(){
        App latestApp=getLatest(tabApp.colInsertDate());
        AppUser latestAppUser=getLatest(tabAppUser.colCreationDate());
        AppRole latestAppRole=getLatest(tabAppRole.colLastUpdateDate());
    }
Finally, we have one method to getLatest object from table... and this method can be put into interface and can implemented in any place... quite comfortably.. isn't?

Tags:
Post Reply