说到整合Spring和Hibernate首先要搞清楚,整合什么?
1、使用Spring的IOC容器来生产Hibernate的SessionFactory对象实例
2、让Hibernate使用Spring的声明式事务
整合步骤
1、先加入Hibernate
2、在加入Spring,整合
新建项目,建立包结构,演示整合
1、导入hibernate的jar包
XML
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
2、新建配置文件

3、生产model类和数据库的表之间的关系映射xml文件
加入Spring
1、导入jar包
XML
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
2、配置Spring,同时也就整合了

补充一点:Hibernate的配置文件可以去掉,它里边的原生的hibernate属性怎么配置呢?

整合就完了吗?不是,我们还要考虑一些问题
web应用中使用Spring框架的时候,Spring的IOC容器的创建时机:应该是在Web应用被载入服务器的时候,就要创建Ioc容器,并且要将Ioc容器放到Web的ServletContext域中!以供Web应用里的类调用!具体应该怎么做呢?看代码!
web.xml

SpringContextListener.java





在真正的web项目中,是不用我们自己去写SpringContextListener这个监听器的,spring已经给我们写好了一个,我们直接在web.xml配置文件中配置就好了!

通过以下utils工具,可以直接获取到Spring的ioc容器,具体内部细节我们可以不关心:
