How can I get last inserted id using Hibernate

后端 未结 4 1975
醉话见心
醉话见心 2020-12-31 11:51

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

After search:

Long lastId = ((Long) session.createSQLQuery(\"SELECT LAST_INSERT_ID()\").         


        
4条回答
  •  粉色の甜心
    2020-12-31 12:36

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

提交回复
热议问题