Working with Data

Most Java applications are driven by data. This means that we need our applications to connect to a database to save or retrieve data.

Updated

Configure the Project

  1. Configure the Project (Journeyman): Add the MySQL driver, commons-dbcp2 and spring-jdbc dependencies to a Maven project's pom.xml so your Java code can work with a MySQL database.

Querying a Database

  1. Querying a Database: an overview (Journeyman): Reading data from a database in Java takes three steps: connect to the database, run an SQL query, and read the results.
  2. JDBC Objects (Journeyman): Meet the three objects that query MySQL from Java: a BasicDataSource to connect, a JdbcTemplate to run SQL, and a SqlRowSet to read the rows that come back.
  3. Full Example (Journeyman): A complete main method that connects to the northwind database, selects every product, and prints each product's id, name and price.

Working with User Input

  1. Working with User Input (Journeyman): Pass user input to a query as a ? parameter instead of joining it into the SQL string, so nobody can run a SQL injection attack on your database.

Mapping Data to Models

  1. Mapping Data to Models: an overview (Journeyman): Storing query results in model objects lets your program reuse the data without querying the database again.
  2. Model Review (Journeyman): A Category model class has a private field, a getter and a setter for each column of the categories table.
  3. Mapping Data to Models (Journeyman): Turn each row of a query result into a Category object and collect them in an ArrayList.
  4. Data Access Objects (Journeyman): A data access object (DAO) is a class that holds the database code for one table, so the rest of your program calls methods like getAllCategories() instead of writing SQL.
  5. Example (Journeyman): A CategoriesDao class loads every category from the database into a list, and Main prints each category's name.