一、Hibnernate 和 Spring结合方案:

    • 方案一:  框架各自使用自己的配置文件,Spring中加载Hibernate的配置文件。
    • 方案二:   统一由Spring的配置来管理。(推荐使用)

二、结合步骤

  2.1   加载框架的jar包

  2.2   框架的配置文件

    hibernate.cfg.xml

<session-factory>
<property name="myeclipse.connection.profile">
com.jdbc.mysql.Driver
</property>
<property name="connection.url">
jdbc:mysql://127.0.0.1:3306/test
</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">
com.p6spy.engine.spy.P6SpyDriver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping class="bean.StudentBean" />
<mapping class="bean.ClassBean" />
<mapping class="bean.BlobBEAN" /> </session-factory>

  spring.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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:component-scan base-package="service"></context:component-scan> <!-- 自动扫描,把 service包里带有@Component注解的类注册为spring上下问的bean--> <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 在spring中加载hiberntae的配置 -->
</bean> </beans>
  • StudentService .java  测试在spring中通过DI方式注入SessionFactory
package service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service; import bean.StudentBean; @Component("studentService")
public class StudentService { @Autowired
private SessionFactory sessionFactory; public void save(){ Session session=null;
Transaction tran=null; try {
session=sessionFactory.getCurrentSession();
tran=session.beginTransaction();
StudentBean stu=new StudentBean();
stu.setStuId(3);
stu.setClassId("3");
stu.setStuName("admin3");
session.save(stu); tran.commit();
} catch (Exception e) {
e.printStackTrace();
tran.rollback();
}finally{
//getCurrentSession无须手动关闭
} } /**
* 测试在spring中通过DI方式注入SessionFactory
   * 本类的save方法的事务是由Hibernate管理的,所以要在hibernate配置文件的设置
   * <property name="current_session_context_class">thread</property>
* @param args
*/
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
StudentService stuService=(StudentService)context.getBean("studentService");
stuService.save();
} }
  • Test_Transaction.java测试在spring管理事务。(Hibernate不再参与事务的提交与回滚)
package test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller; import service.TransactionService; /**
* 测试在spring管理事务。(Hibernate不再参与事务的提交与回滚)
* @author 半颗柠檬、
*
*/ @Controller(value="tranTest")
public class Test_Transaction { @Autowired
private TransactionService tranService; public static void main(String[] args) throws Exception {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml"); Test_Transaction stuTest=(Test_Transaction)context.getBean("tranTest");
stuTest.tranService.save_a(); }
}
  • TransactionService .java
package service;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import dao.StudentDao; @Service
@Transactional
public class TransactionService {
@Autowired
private StudentDao stuDao; public void save_a() throws Exception{
stuDao.save_1();
stuDao.save_2(); } }
  • StudentDao .java
package dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import bean.StudentBean; @Repository(value = "stuDao")
public class StudentDao { @Autowired
private SessionFactory sessionFactory; public void save_1() throws Exception {
Session session = null; try {
session = sessionFactory.getCurrentSession();
StudentBean stu = new StudentBean();
stu.setStuId(15);
stu.setClassId("3");
stu.setStuName("admin3");
session.save(stu);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} } public void save_2() throws Exception {
Session session = null;
try { session = sessionFactory.getCurrentSession();
StudentBean stu = new StudentBean();
stu.setStuId(1);
stu.setClassId("3");
stu.setStuName("admin3");
session.save(stu); } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} } }
  • spring.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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:component-scan base-package="service"></context:component-scan> <!-- 自动扫描,把 service包里带有@Component注解的类注册为spring上下问的bean -->
<context:component-scan base-package="dao"></context:component-scan>
<context:component-scan base-package="test"></context:component-scan> <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 在spring中加载hiberntae的配置 -->
</bean> <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<constructor-arg index="0" name="url"
value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="1" name="username" value="root"></constructor-arg>
<constructor-arg index="2" name="password" value=""></constructor-arg>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
</bean> <!-- 第一种方式:使用xml配置来配置声明式事务 -->
<bean name="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource"></property>
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <tx:advice id="advice_1" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice> <aop:config>
<!-- Pointcut 是指那些方法需要被执行"AOP",是由"Pointcut Expression"来描述的. -->
<aop:pointcut expression="execution(* service.*.*(..))"
id="point_1" />
<aop:advisor advice-ref="advice_1" pointcut-ref="point_1" />
</aop:config> <!-- 第一种方式结束 --> <!-- 第二种方式:使用事务注解来配置声明式事务 --> <bean name="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource"></property>
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" /> <!-- 第二种方式结束 --> </beans>
  • 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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="myeclipse.connection.profile">
com.jdbc.mysql.Driver
</property>
<property name="connection.url">
jdbc:mysql://127.0.0.1:3306/test
</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">
com.p6spy.engine.spy.P6SpyDriver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
<mapping class="bean.StudentBean" />
<mapping class="bean.ClassBean" />
<mapping class="bean.BlobBEAN" /> </session-factory> </hibernate-configuration>
  • 注意:  如果把hibernate的事务交给spring管理,那么配置必须修改为<property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>  ,如果事务还是在hibernate里管理,则<property name="current_session_context_class">thread</property>


全部代码在: 链接

(十七)Hibnernate 和 Spring 整合的更多相关文章

  1. 使用Spring整合Quartz轻松完成定时任务

    一.背景 上次我们介绍了如何使用Spring Task进行完成定时任务的编写,这次我们使用Spring整合Quartz的方式来再一次实现定时任务的开发,以下奉上开发步骤及注意事项等. 二.开发环境及必 ...

  2. 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】

    一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...

  3. spring整合hibernate的详细步骤

    Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibern ...

  4. Spring整合Ehcache管理缓存

    前言 Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它 ...

  5. spring整合hibernate

    spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...

  6. MyBatis学习(四)MyBatis和Spring整合

    MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...

  7. Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来

    转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...

  8. Spring整合HBase

    Spring整合HBase Spring HBase SHDP § 系统环境 § 配置HBase运行环境 § 配置Hadoop § 配置HBase § 启动Hadoop和HBase § 创建Maven ...

  9. Spring整合Ehcache管理缓存(转)

    目录 前言 概述 安装 Ehcache的使用 HelloWorld范例 Ehcache基本操作 创建CacheManager 添加缓存 删除缓存 实现基本缓存操作 缓存配置 xml方式 API方式 S ...

随机推荐

  1. python matplotlib(数据可视化)

    吐槽 网上搜了不少matplotlib安装方法(不信,你可以试试.) 我只能说,除了太繁琐,就是没什么用! 如果你是python3.6.5版本 我给你最最最正确的建议: 直接打开cmd,找到pip用命 ...

  2. 数据库Sequence创建与使用

    最近几天使用Oracle的sequence序列号,发现对如何创建.修改.使用存在很多迷茫点,在上网寻找答案后,根据各路大神的总结,汇总下对自己的学习成果: 在Oracle中sequence就是序号,每 ...

  3. matlab中x.^2与x^2有什么区别?

    .^2是矩阵中的每个元素都求平方,^2是求矩阵的平方或两个相同的矩阵相乘,因此要求矩阵为方阵,且看下面的例子x=1:4x = 1 2 3 4 x.^2 ans = 1 4 9 16 x^2 Error ...

  4. Windows10下Anaconda虚拟环境下安装pycocotools

    0 - 步骤 安装visualcppbuildtools_full.exe(链接:https://blog.csdn.net/u012247418/article/details/82314129) ...

  5. python定义接口继承类

    zxq547 python定义接口继承类invalid syntax解决办法 1 2 3 4 5 6 7 class s_all(metaclass=abc.ABCMeta):     #python ...

  6. Spring Cloud Eureka集群部署到Linux环境

    还是三板斧:先改配置文件,支持集群,然后出包,上传到linux环境(3个节点),最后启动jar包跑起来. 1.在原eureka服务端代码(参见Greenwich.SR2版本的Spring Cloud ...

  7. MySQL数据库备份之xtrabackup工具使用

    一.Xtrabackup备份介绍及原理 二.Xtrabackup的安装 1.在centos7上基于yum源安装percona-xtrabackup软件 [root@node7 ~]# yum -y i ...

  8. 货币转换函数:CURRENCY_CONVERTING_FACTOR

    针对不同币别要做金额栏位转换 计算规则: 金额 = 原始金额 * 转换率 以下转自博客:https://www.cnblogs.com/sanlly/p/3371568.html 货币转换函数:CUR ...

  9. python 类型注解

    函数定义的弊端 python 是动态语言,变量随时可以被赋值,且能赋值为不同类型 python 不是静态编译型语言,变量类型是在运行器决定的 动态语言很灵活,但是这种特性也是弊端 def add(x, ...

  10. Django中使用Bootstrap----带view.py视图函数(也就是项目下的脚本文件)

    一.Django中使用Bootstrap 1.首先建立工程,建立工程请参照:https://www.cnblogs.com/effortsing/p/10394511.html 2.在Firstdja ...