title: Spring JPA - Injecting transaction manager vs injecting entity manager
body: <p>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</p>
  
  <pre><code>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;
    }
  }
  </code></pre>
  
  <p>As apposed to injecting EntityManager directly </p>
  
  <pre><code>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;
        }
      }
  </code></pre>
  
  <p>where as spring config snippet looks like this</p>
  
  <pre><code> &lt;beans&gt;
      &lt;bean id="MyDAO" class="com.xyz.app.dao.MyDAO"&gt;
  
      &lt;context:annotation-config /&gt;
  
      &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean"&gt;
          &lt;property name="persistenceUnitName" value="persistence" /&gt;
          &lt;property name="dataSource" ref="dataSourceProvider" /&gt;
          &lt;property name="jpaVendorAdapter" ref="jpaVendorAdapter" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="transactionManagerJpa" class="org.springframework.orm.jpa.JpaTransactionM anager"&gt;
            &lt;property name="entityManagerFactory" ref="entityManagerFactory"/&gt;
      &lt;/bean&gt;
   &lt;/beans&gt;
  </code></pre>