简体   繁体   English

如何使用HQL(休眠查询语言)获取列的最后一个值

[英]How to get the last value of a column using HQL(Hibernate Query Language)

在此处输入图片说明

As shown in the picture, I need the last value of bookingID column using hibernate in MySQL. 如图所示,我需要在MySQL中使用hibernate的bookingID列的最后一个值。

@SuppressWarnings("unchecked")
    @Override
    public Booking listBookingsID() {
        Session session = this.sessionFactory.getCurrentSession();
        Booking bookList =  (Booking) session.createQuery("from Booking ORDER BY bookid DESC")
                .setMaxResults(1).uniqueResult();


        return bookList;
    }

I tried that code which is found in this link , but it always shows as "9". 我尝试了在此链接中找到的代码,但始终显示为“ 9”。 If the last value is "1" then it should show as 1, but it's 9. 如果最后一个值为“ 1”,则应显示为1,但值为9。

So my question is: "Are there any queries to get the last value of a column in hibernate?" 所以我的问题是:“是否有任何查询来获取休眠中列的最后一个值?”

You can get the Maximum ID of your table like: 您可以通过以下方式获取表的最大ID:

HibernateEntityManager he;

long lastID = ((Number) he.createNativeQuery("select max(id) from table;").getSingleResult()).longValue();

then you can get the bookingID from it with searching for the row with lastID 然后您可以通过搜索带有lastID的行来从中获取BookingID

if you use JPA, it would be like this: 如果您使用JPA,它将是这样的:

long bookingID;
bookingID = bookRepository.findOne(lastID).getBookingID;

A Database table doesn't have a order itself. 数据库表本身没有订单。 So there is no direct way to query for the last entry. 因此,没有直接的方法来查询最后一个条目。

But since your table uses an autoincrement primary key id you can get the last inserted entry by sorting the result by this id in descending order and select the first result 但是由于表使用自动递增的主键id您可以通过按此ID降序对结果进行排序并选择第一个结果来获取最后插入的条目

Booking booking =  (Booking) session.createQuery("from Booking ORDER BY id DESC")
            .setMaxResults(1).uniqueResult();

This will get you the Booking with the highest id , now all you have to do is select the bookingId of that entry: 这将为您提供id最高的Booking,现在您只需选择bookingId目的bookingId

  return booking.getBookingId();

Try this: 尝试这个:

Booking bookList =  (Booking) session.createQuery("from Booking ORDER BY bookid DESC")
    .setMaxResults(1).getSingleResult();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM