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. 03 HttpServletRequest_HttpServletResponse

    HttpServletRequest:一次来自客户端的请求的相关信息 请求行 request.getMethod() 获取http请求方式 request.getRequestURI() 获取统一资源 ...

  2. sit、qas、dev、pet

    SIT: System Integrate Test 系统整合测试 QAS: Quality Assurance system 质量保证 DEV: Development 开发 PET: Perfor ...

  3. Mysql的实现原理

    上篇文章已经简单介绍了Mysql索引的基本介绍,这篇文章主要讲解一下所以的实现原理.索引的定义其实非常复杂,严格的定义需要用到关系代数的概念,不在咱们讨论范围内,这里咱们只讨论mysql的常用的引擎的 ...

  4. Asp.Net Core 2.0 之旅---@Html.Action

    原文:Asp.Net Core 2.0 之旅---@Html.Action 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https: ...

  5. datagrid使用和文字超出tip提示

    function LoadTable(queryData) {             $("#eventInfoTable").datagrid({               ...

  6. xcode 更改svn地址

    xcode如何更改svn地址: 1在控制台 cd进入到项目路径下 命令提示符下输入 $svn info 查看svn信息 修改svn地址 输入如下命令 $svn switch --relocate ht ...

  7. SIP:100rel 扩展

    SIP:100rel 扩展 100rel扩展即是对中间状态响应的确认(即1xx的响应码).原先在sip里,只有针对invite请求的200ok响应才会有ack,那么当中间状态响应携带重要的会话参数信息 ...

  8. nohub

    nohup command > myout.file 2>&1 & nohup command > /dev/null 2>&1 &

  9. 创建守护进程步骤与setsid()

    原创:http://www.cnblogs.com/mickole/p/3188321.html 一,守护进程概述 Linux Daemon(守护进程)是运行在后台的一种特殊进程.它独立于控制终端并且 ...

  10. maven的一些命令以及说明 ——1

    mvn  compile  :  编译源文件 mvn  test-compile : 编译Junit测试文件 mvn test : 运行junit测试文件 mvn package : 编译 + 测试 ...