How to inject JPA EntityManager using spring

后端 未结 3 1739
陌清茗
陌清茗 2020-12-02 15:33

Is it possible to have Spring inject the JPA entityManager object into my DAO class without extending JpaDaoSupport? If yes, does Spring m

相关标签:
3条回答
  • 2020-12-02 15:59

    The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

    0 讨论(0)
  • 2020-12-02 16:05

    Is it possible to have spring to inject the JPA entityManager object into my DAO class whitout extending JpaDaoSupport? if yes, does spring manage the transaction in this case?

    This is documented black on white in 12.6.3. Implementing DAOs based on plain JPA:

    It is possible to write code against the plain JPA without using any Spring dependencies, using an injected EntityManagerFactory or EntityManager. Note that Spring can understand @PersistenceUnit and @PersistenceContext annotations both at field and method level if a PersistenceAnnotationBeanPostProcessor is enabled. A corresponding DAO implementation might look like this (...)

    And regarding transaction management, have a look at 12.7. Transaction Management:

    Spring JPA allows a configured JpaTransactionManager to expose a JPA transaction to JDBC access code that accesses the same JDBC DataSource, provided that the registered JpaDialect supports retrieval of the underlying JDBC Connection. Out of the box, Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on the JpaDialect mechanism.

    0 讨论(0)
  • 2020-12-02 16:13

    Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

    http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

    This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

    0 讨论(0)
提交回复
热议问题