Spring DaoSupport and @PersistanceContext EntityManager?

懵懂的女人 提交于 2019-12-07 10:13:39

问题


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:


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.




回答2:


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




回答3:


I would rather recommend you not to extend JpaDaoSupport, spring will do everything for you. Follow the link suggested by diega for more information, same blog I have followed to upgrade my application to support spring - jpa.



来源:https://stackoverflow.com/questions/1112173/spring-daosupport-and-persistancecontext-entitymanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!