简体   繁体   中英

Get last id of an entity in hibernate

I need a way to fetch the last id of an entity in database, let's say for example

Product entity:

I try this but its not working:

 public int lastInsertedId() {
        try {
            if (!session.isOpen())
                session = DatabaseUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Query query = session.createSQLQuery("select last_value from purchase_idpurchase_seq ");

            int lastid = query.getFirstResult();

            session.getTransaction().commit();
            session.close();
            return lastid;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }


    }

After a bit of Googling, i get the solution:

 public int lastInsertedId() {
        try {
            if (!session.isOpen())
                session = DatabaseUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Criteria c = session.createCriteria(Purchase.class);
            c.addOrder(Order.desc("id"));
            c.setMaxResults(1);
            int id = (int) ((Purchase) c.uniqueResult()).getIdPurchase();
            session.getTransaction().commit();
            session.close();
            return id;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }


    }

Try to use something like this:

   String hql = "from purchase_idpurchase_seq";
   Query query = session.createQuery(hql);
   List<purchase_idpurchase_seq> results = query.list();

And to get the value of last_value try this:

  String last_value = results.getLast_value(); //  if getLast_value return int use int.

I suppose you have an entity purchase_idpurchase_seq

Try to take a look at this site

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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