文章目录
一、Spring和Hibernate整合步骤
参考:https://mp.weixin.qq.com/s/pIMWtg8t8N-CUtvu-lIqkQ
Spring和Hibernate整合的关键点:
——SessionFactory对象交给Spring来创建
——Hibernate的事务交给Spring进行管理
1.1 引入jar包
连接池/数据库驱动包
Hibernate相关jar
Spring 核心包(5个)
Spring aop 包(4个)
spring-orm-3.2.5.RELEASE.jar 【spring对hibernate的支持】
spring-tx-3.2.5.RELEASE.jar 【事务相关】
1.2 配置文件
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<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节点代表一个数据库 -->
<session-factory>
<!-- 1. 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!--数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 2. 其他相关配置 -->
<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 2.2 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- 2.3 自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
1.3 搭建配置环境测试
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();
}
}
1.3.1 测试Spring环境
为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
<?xml version="1.0" encoding="UTF-8"?>
<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);
}
}
1.3.2 测试Hibernate环境
映射配置文件
User.hbm.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<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());
}
}
二、使用Spring创建SessionFactory对象
2.1 直接加载hibernate主配置文件
bean.xml
<!--
SessionFactory是一个工厂,我们要使用它的实现类
我们使用的是hibernate的3.6版本,因此加载的是3
-->
<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();
}
}
2.2 连接池交给Spring管理
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>
<!--加载Hibernate的主配置文件,又使用Spring的数据库连接池-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!--说明配置文件所在的位置-->
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
2.3 配置文件全写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>
<!-- 所有的配置信息都在Spring中完成-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--Hibernate常用的配置属性-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!--Hibernate加载映射文件,映射到具体位置-->
<property name="mappingLocations">
<list>
<value>com/my/entity/User.hbm.xml</value>
</list>
</property>
</bean>
<!-- 包扫描 -->
<context:component-scan base-package="com.my"/>
三、Spring管理事务
到目前为止,我们是使用Hibernate编程式事务控制管理,Spring与Hibernate整合另一个关键就是使用Spring对Hibernate进行事务管理。
注意:Spring与Hibernate整合,Spring只支持线程的Session,并且不用我们手动配置。
注册HibernateTransactionManager类:
bean.xml
<!--配置Hibernate的事务管理器类-->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<!--引用的是SessionFactory,SessionFactory包括了数据连接池-->
<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);
}
}