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. Idea 使用 Junit4 进行单元测试

    目录 Idea 使用 Junit4 进行单元测试 1. Junit4 依赖安装 2. 编写测试代码 3. 生成测试类 4. 运行 Idea 使用 Junit4 进行单元测试 1. Junit4 依赖安 ...

  2. 50道高级sql练习题;大大提高自己的sql能力(附具体的sql)

    问题及描述:--1.学生表Student(SID,Sname,Sage,Ssex) --SID 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别--2.课程表Course(CID ...

  3. js判断是哪种浏览器和阻止页面加载

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  4. Window环境下使用多个Git账号(github,gitee,gitlab,gogs等)

    个人电脑之前已经设置好github账号了,公司用的是gitlab私服,一直互不干扰,因为用的是不同的电脑,也就懒得配置git多账户环境.最近看了一下多年空空如也的码云,想着怎么的也会用到gitee来托 ...

  5. 关于__new__和__init__

    关于__new__和__init__ 例如一个类 class Foo(object): def __init__(self): print(1) def __new__(self): print(2) ...

  6. JS基础 sessionStorage

    html5中的Web Storage包括了两种存储方式:sessionStorage和localStorage. sessionStorage用于本地存储一个会话(session)中的数据,这些数据只 ...

  7. modelsim仿真xilinx ram输出均为0

    现象 在vivado2018.3下生成了RAM IP,丢到modelsim中仿真发现doutb输出均为0.调整AB端口的时钟速率,发现低于5ns不行,输出为0.但5ns以上正常. 解决方法 比对了vi ...

  8. phpstorm+xdebug+mvc

    前一段时间自己琢磨出来,今天又给忘了,还去t00ls发帖.... 写到这里备忘 拿这个yxcms举例子 版本: yxcms1.2.1 源码:http://pan.baidu.com/s/1pJM1CP ...

  9. 实现Vue的双向绑定

    一.概述 之前有讲到过vue实现整体的整体流程,讲到过数据的响应式,是通过Object.defineProperity来实现的,当时只是举了一个小小的例子,那么再真正的vue框架里是如何实现数据的双向 ...

  10. linux cenos开放端口

    问题:8080端口不能访问 解决方案: 第1步 查看阿里云端口是否开放 网络安全>安全组>配置规则>添加入方向 第二步 查看防火墙是否开启(只说开启了防火墙的情况) 查看防火墙状态: ...