[英]Is there an another way to handle exceptions instead of "exceptional handling"?
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.");
}
}
}
}
}
異常處理是處理錯誤的唯一方法。 例如,根據您編寫的應用程序類型,您可以使用 Spring 的 AOP。 這將需要額外的努力來理解面向方面的編程。
評論非常相關,也許您可以詳細說明您要實現的目標。 解釋這是找到答案的最佳方式; 您很可能會被引導到一個全新的解決方案。
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.