步骤:数据源配置-事务配置(xml配置方式或注解方式)
如果要使用注解方式依赖注入sessionFactory到业务Bean中(使用@Resource)或者注入entityManager到业务Bean中(使用@PersistenceContext ),要加入<context:annotation-config/>
1.使用数据源:
<!-- 配置数据源 -->
<bean />
</bean>
<!-- 数据源事务管理器-->
<bean />
</bean>
<!-- 注解方式配置事务 -->
<tx:annotation-driven transaction-manager="txManager"/>
2.使用Hibernate。
(1).配置数据源同上。
(2).配置sessionFactory
<bean >
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
(3).配置事务管理器
<bean />
</bean>
(4).注解方式配置事务同上。
3.使用JPA
(1).配置持久化数据单元
src/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="jpaPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name = "hibernate.connection.driver_class" value = "com.mysql.jdbc.Driver"/>
<property name = "hibernate.connection.url" value = "jdbc:mysql://localhost:3306/hib"/>
<property name = "hibernate.connection.username" value = "root"/>
<property name = "hibernate.connection.password" value = "123456"/>
<property name = "hibernate.hbm2ddl.auto" value = "update"/>
</properties>
</persistence-unit>
</persistence>
(2).配置entityManagerFactory
<bean />
</bean>
(3).配置事务管理器
<bean />
</bean>
(4).注解方式配置事务同上。
分析spring源代码
LocalEntityManagerFactoryBean中的方法createNativeEntityManagerFactory()。由以下代码可以看出Spring可以利用JPA的实现产品(这里是Hibernate)来创建实体管理器工厂(EntityManagerFactory)。
protected EntityManagerFactory createNativeEntityManagerFactory()
throws PersistenceException
{
//日志记录省略
PersistenceProvider provider = getPersistenceProvider();
if (provider != null)
{
EntityManagerFactory emf = provider.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
if (emf == null) {
throw new IllegalStateException("PersistenceProvider [" + provider + "] did not return an EntityManagerFactory for name '" + getPersistenceUnitName() + "'");
}
return emf;
}
return Persistence.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
}
LocalEntityManagerFactoryBean并没有实现EntityManagerFactory接口,配置它得到EntityManagerFactory对象的原因是它实现了spring框架中的FactoryBean接口,从而Spring可以通过调用接口方法getObject等创建EntityManagerFactory实现者的实例。