I want to fetch the last inserted value\'s id in Hibernate.
After search:
Long lastId = ((Long) session.createSQLQuery(\"SELECT LAST_INSERT_ID()\").
You can simply use save which returns a Serializable object that actually is the last insert id. Sample code:
Session session=this.getSessionFactory().getCurrentSession();
int result = -1;
try {
Serializable ser = session.save(paper);
if (ser != null) {
result = (Integer) ser;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
A testing run:
int result = paperService.save(paper);
System.out.println("The id of the paper you just added is: "+result);
and here is the output:
The id of the paper you just added is: 3032
Error is pretty clear. It's returning BigInteger and not long
You have to assign it to a BigInteger. And get longValue() from it.
Since the return type of uniqueResult()
is BigInteger
and not Long
, you should do it like this:
long lastId = session.createSQLQuery("SELECT LAST_INSERT_ID()")
.uniqueResult() // this returns a BigInteger
.longValue(); // this will convert it to a long value
The method uniqueResult()
only returns a BigInteger because of your query SELECT LAST_INSERT_ID()
.
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;
}