Access to auto increment identity field after SQL insert in Java

前端 未结 5 580
栀梦
栀梦 2020-12-28 18:00

Any advice on how to read auto-incrementing identity field assigned to newly created record from call through java.sql.Statement.executeUpdate?

I know h

相关标签:
5条回答
  • 2020-12-28 18:02

    I've always had to make a second call using query after the insert.

    You could use an ORM like hibernate. I think it does this stuff for you.

    0 讨论(0)
  • 2020-12-28 18:05

    @ScArcher2

    Making a second call is extremely dangerous. The process of INSERTing and selecting the resultant auto-generated keys must be atomic, otherwise you may receive inconsistent results on the key select. Consider two asynchronous INSERTs where they both complete before either has a chance to select the generated keys. Which process gets which list of keys? Most cross-database ORMs have to do annoying things like in-process thread locking in order to keep results deterministic. This is not something you want to do by hand, especially if you are using a database which does support atomic generated key retrieval (HSQLDB is the only one I know of which does not).

    0 讨论(0)
  • 2020-12-28 18:11

    The following snibblet of code should do ya':

    PreparedStatement stmt = conn.prepareStatement(sql, 
                                     Statement.RETURN_GENERATED_KEYS);
    // ...
    
    ResultSet res = stmt.getGeneratedKeys();
    while (res.next())
        System.out.println("Generated key: " + res.getInt(1));
    

    This is known to work on the following databases

    • Derby
    • MySQL
    • SQL Server

    For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to SELECT NEXTVAL(...) for the sequence in question.

    Note that the parameters for executeUpdate(...) are analogous.

    0 讨论(0)
  • 2020-12-28 18:17
    ResultSet keys = statement.getGeneratedKeys();
    

    Later, just iterate over ResultSet.

    0 讨论(0)
  • 2020-12-28 18:27

    @ScArcher2 : I agree, Hibernate needs to make a second call to get the newly generated identity UNLESS an advanced generator strategy is used (sequence, hilo...)

    0 讨论(0)
提交回复
热议问题