I am trying to get the last ID inserted on the Java Derby DataBase.
This is a little program that i did, but i think that could be better ways to do that:
Query queryUsuarios = em.createNamedQuery("Usuario.findAll");
List<Usuario> listUsuario = queryUsuarios.getResultList();
int i=0;
for (i = 0; i < listUsuario.size(); i++) {
Usuario verUsuario = em.find(Usuario.class, i);
if(verUsuario != null) {
System.out.println(i+")"+verUsuario.getNombres());
}
}System.out.println("The last ID is "+i);
The main question is, there is a better and more secure way to do this?. Because i think on this way i could get errors in the future...
Thank you!.
You can do it using LIMIT
and order by
.Check below:
SELECT * FROM `table_name` ORDER BY `table_id` desc LIMIT 1;