0

I find the same question How to get last record from Mysql using Hibernate? but i dont solved my problem. I want to get last record from Mysql using Hibernate, this is my code

public class CabinetController implements Controller {

@Override
public ModelAndView handleRequest(HttpServletRequest hsr,
                                  HttpServletResponse hsr1) throws Exception {
    ModelAndView mv = new ModelAndView("kabinet");
    String out = "Výpis uživatelů: ";
    try {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
     List result = session.createQuery("from Kabinet ORDER BY id  desc LIMIT 1").list();
        mv.addObject("kor", result);
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    mv.addObject("message", out);
    return mv;
}

resault is full table whith all records, but I want just 1 last record?

Please help me, it is very important for me!!!

Community
  • 1
  • 1
Orion
  • 59
  • 2
  • 10

2 Answers2

3

Limit does not work in HQL (Hibernate v3+).

You should use MaxResults.

Example with list:

List<Kabinet> result = session.createQuery("from Kabinet ORDER BY id DESC")
                          .setMaxResults(1)
                          .list();

Example with no list:

Kabinet result = (Kabinet) session.createQuery("from Kabinet ORDER BY id DESC")
                              .setMaxResults(1)
                              .uniqueResult();
bradleyfitz
  • 686
  • 4
  • 8
  • When i using this query i get this exeption:javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach> – Orion Jan 11 '14 at 17:25
0

For MySQL:

select * from Kabinet order by id DESC limit 1

For MSSQL:

select top 1 * from Kabinet order by id DESC 

For Oracle:

select * from Kabinet where rownum<2 order by id DESC 
developerwjk
  • 8,619
  • 2
  • 17
  • 33