基本原理:就是由spring来管理hibernate的SessionFactory。
spring管理hibernate配置:不在需要hibernate.cfg.xml文件,所有关于hibernate.cfg.xml文件中的配置都在spring的配置文件中来配置。
-
首先要配置数据源
-
接下来引入properties文件
-
创建LocalSessionFactoryBean来完成spring管理hibernate中的SessionFactory
-
加载hbm.xml配置文件
applicationContext.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 加载properties文件 -->
<context:property-placeholder location="classpath:db.properties" /><!-- 开启注解扫描 @Respostory @Service @Controller-->
<context:component-scan base-package="cn.itheima"/><!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 声明sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 加载连接池 -->
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<value>
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.format_sql=true
</value>
</property>
<!-- 加载注解类 -->
<property name="packagesToScan">
<list>
<value>cn.itheima.domain</value>
</list>
</property>
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 事务注解驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///sshtest
jdbc.username=root
jdbc.password=123
spring整合hibernate后的DAO
spring整合hiberante后,我们的dao只需要继承HibernateDaoSupport类
在HibernateDaoSupport中只需要注入SessionFactory就可以获得到HibernateTemplate,它是对hibernate操作的一个简单封装,可以让我们方便使用原来hibernate的操作.
@Repository("userDao")
public class UserDAOImpl extends HibernateDaoSupport implements IUserDAO {@Autowired
@Qualifier("sessionFactory")
public void setSuperSessionFactory(SessionFactory factory) {
super.setSessionFactory(factory);
}@Override
public void add(User user) {
this.getHibernateTemplate().save(user); // session.save()
}}