import java.sql.SQLException;
public class JDBC {
public void create(User user) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
}
答案 0 :(得分:1)
异常处理是处理错误的唯一方法。根据所编写的应用程序类型,您可以使用Spring的AOP为例。这将需要付出额外的努力来理解面向方面的编程。
这些评论非常相关,也许您可以详细说明您要实现的目标。解释这是找到答案的最佳方法;您很有可能会被带到一个全新的解决方案。
答案 1 :(得分:0)
try-with-resources代码很好,尽管在语法上确实有些参差不齐。
您可能只包装了代码以供重用:
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));