1、概述

1.1、Spring与Hibernate整合关键点

1) Hibernate的SessionFactory对象交给Spring创建。
    2) hibernate事务交给spring的声明式事务管理。

1.2、所用到的jar包

    

2、整合实例(三种方法,推荐使用第三种)

2.1、第一种方式:Spring 配置文件,直接加载 hibernate.cfg.xml 配置文件的方式

User 实体类

 package com.shore.entity;

 /**
* @author DSHORE/2019-11-12
*
*/
public class User {
private Integer id;
private String name;
private Integer age; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

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.shore.entity">
<class name="User">
<id name="id">
<generator class="native"/>
</id>
<property name="name" type="java.lang.String"/>
<property name="age" type="java.lang.Integer"/>
</class>
</hibernate-mapping>

DAO 层(接口+接口实现类)

 //接口类
public interface IUserDao {
public void save(User user);//增
} //接口实现类
public class UserDao implements IUserDao {
//从IoC容器注入SessionFactory
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} @Override //添加
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
}

Service 层

 //接口类
public interface IUserService {
public void save(User user);
} //接口实现类
public class UserService implements IUserService { private IUserDao userDao;
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
} @Override
public void save(User user) {
userDao.save(user);
//int i = 1/0; //人为添加异常,测试事务回滚
}
}

Hibernate 核心配置文件(hibernate.cfg.xml)

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/school</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property> <mapping resource="com/shore/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Spring 配置文件(beans.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- Spring自动去读取Hibernate的配置文件(hibernate.cfg.xml) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean> <!-- DAO层 -->
<bean id="userDao" class="com.shore.dao.impl.UserDao">
<property name="sessionFactory" ref="sessionFactory"></property> <!-- 这里和下面的“配置事务管理器”处对接 -->
</bean> <!-- service层 -->
<bean id="userService" class="com.shore.service.impl.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表DAO层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config> <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
<aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>

测试类

 package com.shore.test;

 import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.shore.entity.User;
import com.shore.service.IUserService; /**
* @author DSHORE/2019-11-12
*
*/
public class MyTest { @Test //添加
public void testSaveUser() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
IUserService userService = (IUserService) context.getBean("userService");
User user = new User();
user.setName("王五");
user.setAge(23);
userService.save(user);
}
}

测试结果图:

     测试成功

2.2、第二种方式:连接池交给spring来管理

【一部分配置写到hibernate中,一部分在spring中完成】

User类、User.bhm.xml、测试类、DAO层与Service层的接口类和实现类的代码都不变(和第一种方式的代码一样);
只有Spring的配置文件(beans.xml)和HIbernate的核心配置文件(hibernate.cfg.xml)的代码不一样,如下所示:

Spring配置文件(beans.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- c3p0数据库连接池配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100"></property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="200"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="2"></property>
</bean> <!-- Spring自动去读取Hibernate的配置文件(hibernate.cfg.xml) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- DAO层 -->
<bean id="userDao" class="com.shore.dao.impl.UserDao">
<property name="sessionFactory" ref="sessionFactory"></property> <!-- 这里和下面的“配置事务管理器”处对接 -->
</bean> <!-- service层 -->
<bean id="userService" class="com.shore.service.impl.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表DAO层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config> <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
<aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>

Hibernate核心配置文件(hibernate.cfg.xml)

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property> <mapping resource="com/shore/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

测试结果图;

    测试成功

2.3、第三种方式:Hibernate核心配置文件(hibernate.cfg.xml)全交给Spring来管理

User类、User.bhm.xml、测试类、DAO层与Service层的接口类和实现类的代码都不变(和第一种方式的代码一样);
只有Spring的配置文件(beans.xml)的代码不一样,并且删除HIbernate的核心配置文件(hibernate.cfg.xml),如下所示:

Spring配置文件(beans.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd" default-autowire="byName"> <!-- c3p0数据库连接池配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100"></property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="200"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="2"></property>
</bean> <!-- Spring自动去读取Hibernate的配置文件(hibernate.cfg.xml) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- c3p0的数据库连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- Hibernate配置 -->
<property name="hibernateProperties">
<props> <!-- 注意:这个是Spring配置文件,故下面的key要写全名,即:前面加上hibernate.xxxxxx -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- Hibernate 映射文件的配置 -->
<!-- Hibernate注解版 -->
<!-- <property name="mappingDirectoryLocations">
<list>
<value>classpath:com/bw/entity/</value>
</list>
</property> --> <!-- Hibernate XML版本配置 -->
<property name="mappingLocations">
<list>
<value>classpath:com/shore/entity/*.hbm.xml</value>
</list>
</property>
</bean> <!-- DAO层 -->
<bean id="userDao" class="com.shore.dao.impl.UserDao">
<property name="sessionFactory" ref="sessionFactory"></property> <!-- 这里和下面的“配置事务管理器”处对接 -->
</bean> <!-- service层 -->
<bean id="userService" class="com.shore.service.impl.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表DAO层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config> <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
<aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>

测试结果图:

    测试成功

    

注意:

如果测试过程中出现这个异常:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxxxx'..........

出现这个异常的可能原因:jdk的版本太高,而我们的jar包的版本太低。

解决方法:在Spring的配置文件(beans.xml)的头文件 包引用连接尾部加上  default-autowire="byName" 即可。(注:首先jar包要导齐,不能少,也不能重复导包,同个版本的jar包 导入两个或多个,可能不会出现异常;但,同个包导入两个不同版本,一定会出现异常)

出现这个异常的详细解决方法:https://www.cnblogs.com/dshore123/p/11874754.html

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/11844233.html

欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

Java进阶知识25 Spring与Hibernate整合到一起的更多相关文章

  1. Spring MVC基础知识整理➣Spring+SpringMVC+Hibernate整合操作数据库

    概述 Hibernate是一款优秀的ORM框架,能够连接并操作数据库,包括保存和修改数据.Spring MVC是Java的web框架,能够将Hibernate集成进去,完成数据的CRUD.Hibern ...

  2. Java进阶知识15 Spring的基础配置详解

    1.SSH各个的职责 Struts2:是web框架(管理jsp.action.actionform等).Hibernate:是ORM框架,处于持久层.Spring:是一个容器框架,用于配置bean,并 ...

  3. Java进阶知识24 Spring的事务管理(事务回滚)

    1.事务控制概述   1.1.编程式事务控制         自己手动控制事务,就叫做编程式事务控制.         Jdbc代码: connection.setAutoCommit(false); ...

  4. Java进阶知识23 Spring对JDBC的支持

    1.最主要的代码 Spring 配置文件(beans.xml) <!-- 连接池 --> <bean id="dataSource" class="co ...

  5. Java进阶知识20 Spring的代理模式

    本文知识点(目录): 1.概念  2.代理模式      2.1.静态代理      2.2.动态代理      2.3.Cglib子类代理 1.概念 1.工厂模式  2. 单例模式 代理(Proxy ...

  6. Java进阶知识17 Spring Bean对象的创建细节和创建方式

    本文知识点(目录): 1.创建细节         1) 对象创建: 单例/多例         2) 什么时候创建?         3)是否延迟创建(懒加载)         4) 创建对象之后, ...

  7. Java进阶知识22 Spring execution 切入点表达式

    1.概述   切入点(execution ):可以对指定的方法进行拦截,从而给指定的类生成代理对象.(拦截谁,就是在谁那里切入指定的程序/方法) 格式: execution(modifiers-pat ...

  8. Java进阶知识21 Spring的AOP编程

    1.概述 Aop:(Aspect Oriented Programming)面向切面编程          功能: 让关注点代码与业务代码分离! 关注点:重复代码就叫做关注点:切面: 关注点形成的类, ...

  9. Java进阶知识18 Spring对象依赖关系的几种写法

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

随机推荐

  1. Skip List(跳跃表)原理详解与实现

    ref : https://dsqiu.iteye.com/blog/1705530   本文内容框架: §1 Skip List 介绍 §2 Skip List 定义以及构造步骤   §3 Skip ...

  2. linux中的内核级防火墙(SELINUX)

    SElinux是基于内核开发出来的一种安全机制,被称之为内核级加强型防火墙,有力的提升了系统的安全性. SElinux的作用分为两方面:1.在服务上面加上标签: 2.在功能上面限制功能 在linux系 ...

  3. SQL Server 2017命令创建新账户(test-user),并分配数据库权限

    -- 1. 创建登录账号USE [master];GOCREATE LOGIN [test-user] WITH PASSWORD = 'xysu7SZ193SNX6E{{HxubPE3}vr',DE ...

  4. Android中ListView的使用

    1.主要概念 ListView用于将大数据集以列表的形式展示. ListView可以看成一个容器,它有如下继承链: View <- ViewGroup <- AdapterView < ...

  5. C++ DLL debug版本在其他PC上缺少依赖的处理方式

    1.正常情况提供给其他人的都是Release版本DLL 2.在需要提供Debug版本时,目标机器上可能会缺少环境,或者和生成DLL的环境不匹配导致DLL无法加载,提示DLL无法找到. 3.使用DLL依 ...

  6. Element-ui-Basic

    一.Layout 布局 1.基础布局 <el-row> <el-col :span="24"><div class="grid-conten ...

  7. Vue路由相关配置

    什么是路由? 1.在以前页面跳转使用的是超链接a标签或者js location.href,而路由是跳转切换组件的跳转方式 2.路由就是监听url的改变并提供相对应的组件用于展示 3.vue-route ...

  8. OpenCV 图象腐蚀形态学操作 全家桶

    图象腐蚀与形态学操作 opencv 1. 通过调用库函数实现图像的腐蚀.膨胀: 2. 通过设置结构元素.元素大小.形态学操作类型实现对图象的形态学操作. 源码(VS2017+OpenCV 4.0) # ...

  9. C和指针--命令行参数

    1.命令行参数 C程序的main函数具有两个形参,第1个通常称为argc,它表示命令行参数的数目.第2个称为argv,它指向一组参数值.由于参数的数目并没有内在的限制,所以argv指向这组参数值(本质 ...

  10. KVM虚拟机高级设置——08 管理远程虚拟机

    在搭建KVM环境——07 带GUI的Linux上安装KVM图形界面管理工具介绍了KVM图形化管理工具,这款工具除了可以管理本地KVM虚拟外,还可以管理远程KVM虚拟机. 输入113机器密码 输入yes ...