views:

716

answers:

2

One of the most difficult things about understand Spring is that Spring supports multiple approaches to the same problem.

So in my application I using injected EntityManager using the @PersistanceContext annotation, for example:

@Repository
public class JpaDao extends JpaDaoSupport implements Dao {

    @PersistenceContext(unitName = "PersistanceUnit", type = PersistenceContextType.EXTENDED)
    private EntityManager em;

Is this approach compatible with extending JpaDaoSupport (which requires injecting in an EntityManager)? To me it looks like two incompatible approaches to the solving the same problem, but I would like some advice from someone who has more experience with Spring.

If I shouldn't be extending JpaDaoSupport, how should I build my DAO using the @PersistenceContext approach?

+1  A: 

For injecting the EntityManager you just need to add the next definition

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

you can get more information about this topic in this post from the oficial blog

diega
I understand how inject the EntityManager, I have that working fine. My issue is more about best practices for Spring DAO.
James McMahon
I think that if you use JPA as an standard approach, forcing you to a Spring solution (i.e. extending JpaSupport) is a no sense. If you keep tied to JPA+EJB3 injection you can migrate your jars to an Application Server whenever you want.My 2 micro cents :)
diega
+3  A: 

You're correct that they are two different approaches to the same problem. Which one is "better" is a matter of taste, I think. Using annotations has the benefit of avoiding Spring import dependencies in your code, and even the Spring JavaDoc for JpaDaoSupport suggests using them for new JPA projects. JpaDaoSupport is there to make Spring's support for JPA equivalent to its support for other ORM strategies (HibernateDaoSupport, JdbcDaoSupport, TopLinkDaoSupport, etc.). In those cases, annotation-based injection isn't an option.

Rob H
Thanks for the clarification Rob.
James McMahon