HibernateTransactionManager 或 JpaTransactionManager
与朋友一起开发应用程序,但遇到了一个问题...我有这个代码:
<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>
他说,这是更好的方法,但没有确切解释为什么。关于不直接使用休眠,这是否意味着我们不再使用休眠?这真的是更好的方法吗?
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);
}