PV168

Databases II


JDBC: Architecture

bg 50%


JDBC API

bg 50%


JDBC Connection


JDBC Connection Pooling


Code Sample

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
}

JDBC (Prepared) Statement


JDBC ResultSet


Code Sample

// 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");
        }
    }
}


Code Sample: Transaction

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
}


Employee Records Architecture


bg 40%

Layers Diagram


Data Layer


Business / Model Layer


Connecting Data and Business


Why such separation?


Validation

Database specific validation:


Seminar Reflection


Enum Representation


Application State Initialization

Task 3: Departments are missing in the application

Possible solutions (not all):


Problems with Data Initialization