1

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


    }
abdou amer
  • 819
  • 2
  • 16
  • 43

2 Answers2

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


    }
abdou amer
  • 819
  • 2
  • 16
  • 43
  • You **have** to use `currval()` or `lastval()` (the link I already posted in my first comment) to get the recently generated sequence value. Your code is not going to work properly if more than one transaction is modifying the database. Plus: I'm pretty sure Hibernate should be able to do that natively. Isn't there a "SequenceGenerator" annotation for Hibernate –  Feb 01 '16 at 12:33
0

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

Abdelhak
  • 8,299
  • 4
  • 22
  • 36