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:
Create a class annotated with
@Repository
:@Repository public class UserDAO {
Add an autowired
JdbcTemplate
field to it:@Autowired 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.