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;
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.
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.
Error is pretty clear. It's returning BigInteger
and not long
You have to assign it to a BigInteger
. And get longValue()
from it.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With