Skip to content

A reflection on implementation

Overview

Let's revisit the implementation of createCourse in JdbcCourseCrudPersister:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// PRE: id of course is not set yet.
public void createCourse(Course course) throws SQLException {
  String sql = "INSERT INTO Courses (name, url) VALUES (?, ?);";
  PreparedStatement pst = conn.prepareStatement(sql,
      Statement.RETURN_GENERATED_KEYS);
  pst.setString(1, course.getName());
  pst.setString(2, course.getUrl());

  pst.executeUpdate();
  ResultSet rs = pst.getGeneratedKeys();
  rs.next();
  course.setId(rs.getInt(1));
}

The createCourse method is, in a way, a mapping between a Course object and a record in the Courses table.

To map an object into a record, it requires some work to get the value of each attribute and set it in the corresponding column in the table. Imagine if Course had many more fields; it seems like there must be a better way to map an object into a record (in a relational database); someone must have had this problem and thought of writing a library to solve this problem (at least as long as the fields - in a class - correspond directly to the columns in a table)!

Well, you will not be surprised to learn there exist libraries called Object Relational Mapping (ORM) to solve this problem. We will next explore a simple ORM called Sql2o.