Display the last 10 rows of the database

458 Views Asked by At

Question: Hello everyone, I am working on a project with Richfaces I want to display the last 10 rows of my database (MySQL), this is part of the code I use to display all the rows saved in my database CompanyBean.java Code :

  public class EntrepriseBean implements Serializable{
private List<Entreprise> tableEntreprise ;
 
public List<Entreprise> getTableEntreprise() {
 
        ud= new EntrepriseDAO();
        tableEntreprise=ud.getAll();
 
        return tableEntreprise;
    }
 
    public void setTableEntreprise(List<Entreprise> tableEntreprise) {
        this.tableEntreprise = tableEntreprise;
    }
}

if you have any idea it will be very useful for me. thank you.

1

There are 1 best solutions below

0
On

As some comments are referring, it's not clear what last 10 means. In my opinion there are two good approaches. In your code, you could do something like this

public List<Entreprise> getTableEntreprise() {

    ud = new EntrepriseDAO();
    tableEntreprise = ud.getAll();

    return tableEntreprise.stream().limit(10).collect(Collectors.toList());
}

Another approach would be to the changes SQL statement and use limit, something like this

SELECT * FROM enterprise
ORDER BY creation_time
LIMIT 10

This is assuming creation_time is a field in your table. Alternatively, you can order by id if it's auto-generated, it will have a bit better performance.