我发现同样的问题How to get last record from Mysql using Hibernate?,但我没有解决我的问题。我想使用Hibernate从Mysql获取最后一条记录,这是我的代码
公共类CabinetController实现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是所有记录的全表,但我只想要最后一条记录?
请帮助我,这对我来说非常重要!!!
答案 0 :(得分:2)
限制在HQL(Hibernate v3 +)中不起作用。
你应该使用MaxResults。
列表示例:
List<Kabinet> result = session.createQuery("from Kabinet ORDER BY id DESC")
.setMaxResults(1)
.list();
没有列表的示例:
Kabinet result = (Kabinet) session.createQuery("from Kabinet ORDER BY id DESC")
.setMaxResults(1)
.uniqueResult();
答案 1 :(得分:0)
对于MySQL:
select * from Kabinet order by id DESC limit 1
对于MSSQL:
select top 1 * from Kabinet order by id DESC
对于Oracle:
select * from Kabinet where rownum<2 order by id DESC