Annotations used for configuring DAO or Repository classes - Java-Springs

The best way to guarantee that your Data Access Objects (DAOs) or repositories provide exception translation is to use the @Repository annotation.This annotation also allows the component scanning support to find and configure your DAOs and repositories without having to provide XML configuration entries for them.

@Repository
public class SomeMovieFinder implements MovieFinder {
// ...
}

Any DAO or repository implementation will need to access to a persistence resource, depending on the persistence technology used; for example, a JDBC-based repository will need access to a JDBC DataSource; a JPA-based repository will need access to an Entity Manager.The easiest way to accomplish this is to have this resource dependency injected using one of the @Autowired, @Resource or @Persistence Context annotations. Here is an example for a JPA repository:

@Repository
public class JpaMovieFinder implements MovieFinder {
@PersistenceContext
private EntityManager entityManager;
// ...
}

If you are using the classic Hibernate APIs than you can inject the SessionFactory:

@Repository
public class HibernateMovieFinder implements MovieFinder {
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// ...
}

Last example we will show here is for typical JDBC support. You would have the Data Source injected into an initialization method where you would create a Jdbc Template and other data access support classes like SimpleJdbcCall etc using this DataSource.

@Repository
public class JdbcMovieFinder implements MovieFinder {
private JdbcTemplate jdbcTemplate;
@Autowired
public void init(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
// ...
}

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java-Springs Topics