con.setAutoCommit(false)
con.commit()
/ con.rollback()
is requiredJdbcConnectionPool
(simple implementation) implements DataSource
interface (like most connection pool implementations)Connection pool example
String jdbcUri = "jdbc:h2:/db/path;DATABASE_TO_UPPER=false";
String userName = "databaseUsername"
String password = "databasePassword"
DataSource dataSource = JdbcConnectionPool.create(jdbcUri, username, password);
// After the {Connection#close()} is called,
// it is returned to the connection pool
try(Connection connection = dataSource.getConnection()) {
// Perform the operations
}
Statement
!!!PreparedStatement
protects against SQL InjectionPreparedStatement
)// connection and statement should be both closed after we are done
try(
Connection connection = dataSource.getConnection();
var statement = connection.prepareStatement("SELECT id, number FROM Department WHERE id = ?")
) {
ps.setLong(1, departmentID); // set the
try (var rs = statement.executeQuery()) { // we should close the result set
while (rs.next()) {
long departmentId = rs.getLong("id");
String number = rs.getString("number");
}
}
}
try(Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try(var st = connection.prepareStatement("INSERT INTO ...")) {
st.executeUpdate();
}
...
if(isSomeError)
connection.rollback(); // maunal rollback
...
try(var st = connection.prepareStatement("UPDATE ...")) {
st.executeUpdate();
}
connection.commit(); // manual commit
}
ConnectionHandler
Database specific validation:
VARCHAR
and other database types have fixed sizeDepartment.number
max length is 10 charactersgender ENUM('male', 'female')
VARCHAR
and check if database supports itTask 3: Departments are missing in the application
Possible solutions (not all):
data_dev.sql
)DataInit
~> ProductionDataInit