Get last id of an entity in hibernate

2.8k Views Asked by At

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;
        }


    }
2

There are 2 best solutions below

2
Abdelhak On

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

1
abdou amer On

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;
        }


    }