0

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.

Dupinder Singh
  • 7,175
  • 6
  • 37
  • 61
  • Define "Last 10 rows": Are you using an autoincrement ID and talking about the rows with the 10 highest IDs? Do your database entries have some date/time field and you want to get the 10 records with the highest values there or something similar? – OH GOD SPIDERS May 11 '21 at 10:31
  • Most likely best to solve this on the sql level if you have a lot of objects and then use `ORDER BY x desc` together with a limit of 10, syntax will of course depend on what RDBMS you are using. – Joakim Danielson May 11 '21 at 10:31
  • You can use lazy loading. Then with fetch you can display first 10, last 10, records per any specific page, ... as you need. You can specify default sorting and your first page can display data ordered in descending order, which may represent last 10 records. – Vasil Lukach May 23 '21 at 01:56

1 Answers1

0

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.

mihajlo
  • 71
  • 5