Skip to content

What is the difference between Transaction manager and Entity Manager

As a student, i read nearly all spring documentation. As far as i understood that spring is configuration monster. Annotation based or Xml based, it doesn’t matter but what i really don’t understand is what is the difference between transaction manager and entity manager.

If we have injected entityManager on Dao layer, why do we need transaction manager on service layer or vice versa. If we inject transaction manager(that wraps entitymanager) why do we need to inject entitymanager on DaoLayer. For JPARepositories, i don’t even need to inject any manager. Spring does everything for me(i don’t really understand mechanics). My another question is for JPARepositories Spring uses entityManager or transactionManager?


TransactionManager is totally different to EntityManager, one is in charge of the entities (listener, entities, relationships, persistence lifecycle of them and this interface defines the methods that are used to interact with the persistence context) associated with an specific persistence context where the entities are alive, meanwhile TransactionManager is responsible for transactional data access, giving support to all the transaction that need to occurs within your application.

Configuration bind one entitymanager object to an specific transactionmanager.

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <qualifier value="pagTransactionManager" />

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />

Which it means the connection to the database and entities are managed by the EntityManager, but the object that open an close transaction in the service layer using the @Transaction annotation is the TransactionManager.

The javax.transaction.TransactionManager interface allows the application server to control transaction boundaries on behalf of the application being managed, this interface contains a lot of method that are using to control them such as : commit, suspend, rollback.

So basically inject one of these objects depends on what you are looking for, manage entities and operate with them use entitymanager, control the transactional state of your application by yourself use the transactionmanager.