参考:https://mp.weixin.qq.com/s/pIMWtg8t8N-CUtvu-lIqkQ
Spring和Hibernate整合的关键点:
——SessionFactory对象交给Spring来创建
——Hibernate的事务交给Spring进行管理
连接池/数据库驱动包
Hibernate相关jar
Spring 核心包(5个)
Spring aop 包(4个)
spring-orm-3.2.5.RELEASE.jar 【spring对hibernate的支持】
spring-tx-3.2.5.RELEASE.jar 【事务相关】
bean.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
beans>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8property>
<property name="hibernate.connection.username">rootproperty>
<property name="hibernate.connection.password">123456property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialectproperty>
<property name="hibernate.show_sql">trueproperty>
<property name="hibernate.format_sql">trueproperty>
<property name="hibernate.hbm2ddl.auto">updateproperty>
session-factory>
hibernate-configuration>
User.java
public class User {
private String name;
private String password;
private int id;
}
IUser.java
public interface IUser {
void save();
}
UserDao.java
public class UserDao implements IUser {
@Override
public void save() {
}
}
UserService.java
public class UserService {
private UserDao userDao;
public void save() {
userDao.save();
}
}
为userDao、userService使用Spring来创建对象,以及添加对象的依赖关系,看看Spring的环境是否成功。
创建UserDao实例—>@Repository
UserDao.java
@Repository
public class UserDao implements IUser {
@Override
public void save() {
}
}
创建userService实例,并注入userDao属性
UserService.java
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void save() {
userDao.save();
}
}
在Spring配置文件中使用注解扫描器
bean.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.my"/>
beans>
测试:成功得到userService对象,并且userService对象含有userDao属性的值
public class Test {
@Test
public void test1() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
UserService userService = (UserService) ac.getBean("userService");
System.out.println(userService);
}
}
映射配置文件
User.hbm.xml
<hibernate-mapping package="com.my.entity">
<class name="User" table="t_user">
<id name="id" column="user_id">
<generator class="native"/>
id>
<property name="name" column="name"/>
<property name="password" column="password"/>
class>
hibernate-mapping>
主配置文件加载映射文件
Hibernate.cfg.xml
<mapping resource="com/my/entity/User.hbm.xml" />
创建SessionFactory,Session
@Repository
public class UserDao implements IUser {
@Override
public void save(User user) {
//得到SessionFactory
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//得到Session
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
测试
public class Test2 {
@Test
public void test2() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
UserService userService = (UserService) ac.getBean("userService");
userService.save(new User());
}
}
bean.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
bean>
那么在userDao中就不用我们自己手动来创建SessionFactory对象了。
@Repository
public class UserDao implements IUser {
@Autowired
private SessionFactory sessionFactory;
@Override
public void save(User user) {
//得到Session
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Hibernate对C3P0的连接池支持度比不上Spring,因此可以使用Spring的连接池。因此我们加载Hibernate的主配置文件又使用Spring的数据库连接池。即一部分配置在hibernate.cfg.xml,一部分配置在Spring文件中。
bean.xml
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
<property name="initialPoolSize" value="3"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatements" value="100"/>
<property name="acquireIncrement" value="2"/>
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="dataSource" ref="dataSource"/>
bean>
推荐
bean.xml
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
<property name="initialPoolSize" value="3"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatements" value="100"/>
<property name="acquireIncrement" value="2"/>
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
props>
property>
<property name="mappingLocations">
<list>
<value>com/my/entity/User.hbm.xmlvalue>
list>
property>
bean>
<context:component-scan base-package="com.my"/>
到目前为止,我们是使用Hibernate编程式事务控制管理,Spring与Hibernate整合另一个关键就是使用Spring对Hibernate进行事务管理。
注意:Spring与Hibernate整合,Spring只支持线程的Session,并且不用我们手动配置。
注册HibernateTransactionManager类:
bean.xml
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
bean>
<tx:annotation-driven transaction-manager="txManager"/>
UserDao.java
@Repository
public class UserDao implements IUser {
@Autowired
private SessionFactory sessionFactory;
@Override
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
}
UserService类添加@Transactional注解就是为Hibernate添加了事务管理了。
UserService.java
@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
public void save(User user) {
userDao.save(user);
}
}