Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get last inserted id using Hibernate

I want to fetch the last inserted value's id in Hibernate.

After search:

Long lastId = ((Long) session.createSQLQuery("SELECT LAST_INSERT_ID()").uniqueResult()).longValue();

But the following code gives me this error:

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

Please share your thoughts!

Solution

Long lastId = ((BigInteger) session.createSQLQuery("SELECT LAST_INSERT_ID()").uniqueResult()).longValue();

Don't forget to import:

import java.math.BigInteger;

like image 324
Mohit Bhansali Avatar asked Feb 17 '14 12:02

Mohit Bhansali


People also ask

How do I get last inserted data?

you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it. Show activity on this post. For any last inserted record will be get through mysql_insert_id() If your table contain any AUTO_INCREMENT column it will return that Value.

How can I get the last inserted ID from a table in SQL?

To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.


2 Answers

Error is pretty clear. It's returning BigInteger and not long

You have to assign it to a BigInteger. And get longValue() from it.

like image 183
Suresh Atta Avatar answered Oct 16 '22 16:10

Suresh Atta


public Integer save(Smartphones i) {
    int id = 0;
    Session session=HibernateUtil.getSessionFactory().openSession();
    Transaction trans=session.beginTransaction();
    try{
        session.save(i);   
        id=i.getId();
        trans.commit();     
    }
    catch(HibernateException he){}
    return id;
}
like image 24
surya handoko Avatar answered Oct 16 '22 17:10

surya handoko