Annotations Used to Configure DAO or Repository Classes
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
lets the component scanning support find and configure your DAOs and repositories
without having to provide XML configuration entries for them. The following example shows
how to use the @Repository
annotation:
@Repository (1)
public class SomeMovieFinder implements MovieFinder {
// ...
}
1 | The @Repository annotation. |
@Repository (1)
class SomeMovieFinder : MovieFinder {
// ...
}
1 | The @Repository annotation. |
Any DAO or repository implementation needs access to a persistence resource,
depending on the persistence technology used. For example, a JDBC-based repository
needs access to a JDBC DataSource
, and a JPA-based repository needs access to an
EntityManager
. The easiest way to accomplish this is to have this resource dependency
injected by using one of the @Autowired
, @Inject
, @Resource
or @PersistenceContext
annotations. The following example works for a JPA repository:
@Repository
public class JpaMovieFinder implements MovieFinder {
@PersistenceContext
private EntityManager entityManager;
// ...
}
@Repository
class JpaMovieFinder : MovieFinder {
@PersistenceContext
private lateinit var entityManager: EntityManager
// ...
}
If you use the classic Hibernate APIs, you can inject SessionFactory
, as the following
example shows:
@Repository
public class HibernateMovieFinder implements MovieFinder {
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// ...
}
@Repository
class HibernateMovieFinder(private val sessionFactory: SessionFactory) : MovieFinder {
// ...
}
The last example we show here is for typical JDBC support. You could have the
DataSource
injected into an initialization method or a constructor, where you would create a
JdbcTemplate
and other data access support classes (such as SimpleJdbcCall
and others) by using
this DataSource
. The following example autowires a DataSource
:
@Repository
public class JdbcMovieFinder implements MovieFinder {
private JdbcTemplate jdbcTemplate;
@Autowired
public void init(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
// ...
}
@Repository
class JdbcMovieFinder(dataSource: DataSource) : MovieFinder {
private val jdbcTemplate = JdbcTemplate(dataSource)
// ...
}
See the specific coverage of each persistence technology for details on how to configure the application context to take advantage of these annotations. |