简体   繁体   中英

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;

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

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM