Jaanus
Jaanus

Reputation: 16541

HibernateTransactionManager or JpaTransactionManager

Developing application with friend, but ran into a question... I had this code :

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${jdbc.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven />
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="dataSource" ref="dataSource" />
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

And he removed it all, changed it to:

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

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="persistenceUnit"/>
    <property name="dataSource" ref="dataSource"/>
</bean>

He said, that this is better approach, but did not exactly explain why. Something about not using hibernate directly, does this mean we are not using hibernate at all anymore? Is it really better approach?

DAO changed like this:

I had:

@Autowired
private SessionFactory sessionFactory;

public void addUser(User user) {
    sessionFactory.getCurrentSession().save(user);
}

Now is:

@PersistenceContext
private EntityManager entityManager;

public void addUser(User user) {
    entityManager.persist(user);
}

Upvotes: 47

Views: 31612

Answers (1)

Aleksander Blomsk&#248;ld
Aleksander Blomsk&#248;ld

Reputation: 18552

He wants your code to be dependent on JPA, instead of Hibernate. javax.persistence.EntityManager is a JPA (Java EE) standard interface, while org.hibernate.SessionFactory is a Hibernate propertary interface. Moving from SessionFactory to EntityManager makes your classes no longer dependent on Hibernate. Using the JPA-way instead of the Hibernate-way is considered best practice by most people today.

Please note that your system is still dependent upon Hibernate, as you need a JPA provider. But if you want to change to another JPA provider in the future it should be pretty straight forward. Another advantage for going for JPA is that the JPA-interfaces are more stable than the Hibernate ones.

Upvotes: 64

Related Questions