Java 如何使用 Hibernate 获取最后插入的 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21829023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:56:38  来源:igfitidea点击:

How can I get last inserted id using Hibernate

javamysqlhibernatestruts2

提问by Mohit Bhansali

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

我想在 Hibernate 中获取最后插入的值的 id。

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

java.lang.ClassCastException: java.math.BigInteger 不能转换为 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;

导入 java.math.BigInteger;

采纳答案by Suresh Atta

Error is pretty clear. It's returning BigIntegerand not long

错误很明显。它正在返回BigInteger而不是long

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

您必须将其分配给BigInteger. 并从中获得longValue()

回答by bobbel

Since the return type of uniqueResult()is BigIntegerand not Long, you should do it like this:

由于uniqueResult()isBigInteger和 not的返回类型Long,您应该这样做:

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

uniqueResult()由于您的查询,该方法仅返回一个 BigInteger SELECT LAST_INSERT_ID()

回答by surya handoko

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

回答by Linyun Liu

You can simply use save which returns a Serializable object that actually is the last insert id. Sample code:

您可以简单地使用 save 返回一个 Serializable 对象,该对象实际上是最后一个插入 id。示例代码:

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