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
- 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
- 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.
- 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.
- 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
- 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
- Mapping Data to Models: an overview (Journeyman): Storing query results in model objects lets your program reuse the data without querying the database again.
- Model Review (Journeyman): A Category model class has a private field, a getter and a setter for each column of the categories table.
- Mapping Data to Models (Journeyman): Turn each row of a query result into a Category object and collect them in an ArrayList.
- 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.
- Example (Journeyman): A CategoriesDao class loads every category from the database into a list, and Main prints each category's name.