1. 引言
在使用JDBC向数据库插入数据时,获取自动生成的主键是常见需求。JDBC提供了在插入操作后立即获取插入ID的机制。
本文将讨论如何在插入操作后立即获取插入ID。
2. 环境准备
在实现获取插入ID的逻辑前,我们先完成必要的准备工作。
为测试实现,我们将使用内存数据库H2。在pom.xml中添加h2数据库依赖:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
在测试环境中,我们将连接H2数据库并创建示例表EMPLOYEES:
private static void populateDB() throws SQLException {
String createTable = """
CREATE TABLE EMPLOYEES (
id SERIAL PRIMARY KEY ,
first_name VARCHAR(50),
last_name VARCHAR(50),
salary DECIMAL(10, 2)
);
""";
PreparedStatement preparedStatement = connection.prepareStatement(createTable);
preparedStatement.execute();
}
3. 获取插入ID
当执行插入语句时,如果表有自动生成的键(如MySQL的AUTO_INCREMENT、PostgreSQL的SERIAL或H2的IDENTITY),JDBC可通过*getGeneratedKeys()*方法获取这些键。
*插入记录时,我们使用preparedStatement.executeUpdate(),它返回更新的行数。要获取插入ID,需使用Statement.RETURN_GENERATED_KEYS标志:*
String sql = "INSERT INTO employees (first_name, last_name, salary) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, "first");
statement.setString(2, "last");
statement.setDouble(3, 100.0);
int numRows = statement.executeUpdate();
*现在调用statement.getGeneratedKeys()获取ResultSet,通过getLong()提取插入的ID:*
ResultSet generatedKeys = statement.getGeneratedKeys();
List<Long> insertIds = new ArrayList<>();
while(generatedKeys.next()){
insertIds.add(generatedKeys.getLong(1));
}
上述代码中,getLong(1)获取ResultSet中的第一个生成键。若插入操作产生多个生成键,可通过位置访问(如*getLong(2)获取第二个键),或通过列标签访问(如getLong("id1")*)。
通过单元测试验证结果:
@Test
public void givenDBPopulated_WhenGetInsertIds_ThenReturnsIds() throws SQLException {
GetInsertIds getInsertIds = new GetInsertIds();
List<Long> actualIds = getInsertIds.insertAndReturnIds(connection);
ResultSet resultSet = connection.prepareStatement("select id from employees").executeQuery();
List<Long> expectedIds = new ArrayList<>();
while (resultSet.next()){
expectedIds.add(resultSet.getLong(1));
}
assertEquals(expectedIds, actualIds);
}
4. 总结
本文讨论了使用JDBCPreparedStatement获取插入记录ID的机制,实现了相关逻辑并通过单元测试验证。
完整示例代码可在GitHub获取。