简体   繁体   English

Spring JPA - 注入事务管理器与注入实体管理器

[英]Spring JPA - Injecting transaction manager vs injecting entity manager

If I wanted manage transactions programmatically, what is the difference between starting the transaction by injecting a PlatformTransactionManager vs directly injecting EntityMangerFactory/EntityManager and getting transaction from Entitymanager 如果我想以编程方式管理事务,通过注入PlatformTransactionManager与直接注入EntityMangerFactory / EntityManager并从Entitymanager获取事务来启动事务有什么区别?

public class MyDAO  {
@PersistenceContext(unitName="test") EntityManager em;

JpaTransactionManager txnManager = null;
public void setTxnManager(JpaTransactionManager mgr) {
  txnManager = mgr;
}

public void process(Request request) throws Exception {
  TransactionStatus status =
     txnManager.getTransaction(new DefaultTransactionDefinition());
  try {
     em.persist(request);
     txnManager.commit(status);
  } catch (Exception up) {
     txnManager.rollback(status);
     throw up;
  }
}

As apposed to injecting EntityManager directly 如同直接注入EntityManager一样

public class MyDAO {
    @PersistenceContext(unitName="test")
    EntityManager em;

    public void process(Request request) throws Exception {
      EntityTransaction txn = em.getTransaction();
      try {
         em.persist(request);
         txn.commit();
      } catch (Exception up) {
         txn.rollback();
         throw up;
      }
    }

where as spring config snippet looks like this 弹簧配置片段看起来像这样

 <beans>
    <bean id="MyDAO" class="com.xyz.app.dao.MyDAO">

    <context:annotation-config />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
        <property name="persistenceUnitName" value="persistence" />
        <property name="dataSource" ref="dataSourceProvider" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    </bean>

    <bean id="transactionManagerJpa" class="org.springframework.orm.jpa.JpaTransactionM anager">
          <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
 </beans>

Transaction managers should not be injected into DAOs, because a DAO has no way to tell whether they're one participant in a larger transaction or not. 不应将事务管理器注入DAO,因为DAO无法判断它们是否是更大事务中的一个参与者。

I think the transaction manager belongs with the service layer, not the persistence layer. 我认为事务管理器属于服务层,而不是持久层。 The services know about use cases and units of work. 这些服务了解用例和工作单元。 They orchestrate other services, DAOs and model objects to fulfill their use cases. 他们协调其他服务,DAO和模型对象以完成其用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM