How can I get last inserted id using Hibernate

后端 未结 4 1950
醉话见心
醉话见心 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:29

    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
    
    0 讨论(0)
  • 2020-12-31 12:30

    Error is pretty clear. It's returning BigInteger and not long

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

    0 讨论(0)
  • 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().

    0 讨论(0)
  • 2020-12-31 12:46
    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;
    }
    
    0 讨论(0)
提交回复
热议问题