Junior — Middle
Can you explain the purpose of the @Repository annotation in Spring and how it is used in working with databases?
sobes.tech AI
Answer from AI
The @Repository annotation in Spring is used to designate a class as a component responsible for data access (DAO — Data Access Object). It serves as a marker for Spring to automatically register this class as a bean and apply specific processing to it, such as translating database exceptions into unified Spring exceptions (DataAccessException).
Using @Repository helps to:
- Organize the data access layer.
- Ensure automatic exception handling related to the database.
- Integrate with Spring mechanisms such as transactions.
Example:
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public User findById(Long id) {
return jdbcTemplate.queryForObject(
"SELECT * FROM users WHERE id = ?",
new Object[]{id},
new BeanPropertyRowMapper<>(User.class));
}
}