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.");
}
}
}
}
}
Exception handling is the only way for handling errors. Depending on the type of application you're writing, you could use a Spring's AOP for example. That would require an extra effort to understand aspect-oriented programing.
The comments are very relevant, maybe you can elaborate on what you are trying to achieve. Explaining that is the best way to find an answer; most likely you will be directed to a whole new solution.
The try-with-resources code is fine, though syntactically indeed a bit ragged.
You might just wrap the code for reuse:
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.