Код попытки с ресурсами в порядке, хотя синтаксически он действительно немного неровный.
Вы можете просто обернуть код для повторного использования:
public <DTO> void create(DTO dto, DataSource dataSource, String insertSQL,
BiConsumer<PreparedStatement, DTO> paramSetter,
BiConsumer<DTO, Long> primaryKeySetter) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(insertSQL,
Statement.RETURN_GENERATED_KEYS);
) {
parameterSetter.apply(statement, dto);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
primaryKeySetter.apply(dto, generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
create(user, dataSource, SQL_INSERT,
statement -> {
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
},
(dto, id) -> dto.setId(id));