How to get the insert ID in JDBC?

后端 未结 12 2173
暖寄归人
暖寄归人 2020-11-21 06:09

I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can

12条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 06:25

    With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query

    INSERT INTO bla (a,b) VALUES (2,3) RETURNING id
    

    like

    INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1
    

    if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).

提交回复
热议问题