Book Image


Book Image


Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
About the Author
About the Reviewers

Creating a DAO class

In this recipe, we will create a DAO (data access object) class. A DAO class provides methods to save and retrieve objects from the database. It can be used from a controller, for example:

The controller calls the findUsers() method from UserDAO, which takes care of getting the results from the database (using the JdbcTemplate bean defined in the previous recipe).

How to do it…

Here are the steps to create a DAO class:

  1. Create a class annotated with @Repository:

    public class UserDAO {
  2. Add an autowired JdbcTemplate field to it:

    private JdbcTemplate jdbcTemplate;

How it works…

@Repository allows the UserDAO class to be automatically discovered and instantiated as a bean.

The JdbcTemplate field will be initialized automatically by Spring via dependency injection with the JdbcTemplate bean defined in the previous recipe.