一尘不染

HibernateTransactionManager或JpaTransactionManager

hibernate

与朋友一起开发应用程序,但遇到一个问题…我有以下代码:

<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>

然后他删除了所有内容,将其更改为:

<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>

他说,这是更好的方法,但没有确切解释原因。 关于不直接使用hibernate方式的问题,这是否意味着我们不再使用hibernate方式了?这真的更好吗?

DAO更改如下:

我有:

@Autowired
private SessionFactory sessionFactory;

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

现在是:

@PersistenceContext
private EntityManager entityManager;

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

阅读 651

收藏
2020-06-20

共1个答案

一尘不染

他希望您的代码依赖于JPA,而不是Hibernate。javax.persistence.EntityManager是JPA(Java
EE)标准接口,同时org.hibernate.SessionFactory是Hibernate专有接口。从SessionFactory移到EntityManager会使您的类不再依赖于Hibernate。如今,大多数人认为使用JPA-
way而不是Hibernate-way是最佳实践。

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.

2020-06-20