一、Hibnernate 和 Spring结合方案:

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

二、结合步骤

  2.1   加载框架的jar包

  2.2   框架的配置文件

    hibernate.cfg.xml

  1. <session-factory>
  2. <property name="myeclipse.connection.profile">
  3. com.jdbc.mysql.Driver
  4. </property>
  5. <property name="connection.url">
  6. jdbc:mysql://127.0.0.1:3306/test
  7. </property>
  8. <property name="connection.username">root</property>
  9. <property name="connection.password"></property>
  10. <property name="connection.driver_class">
  11. com.p6spy.engine.spy.P6SpyDriver
  12. </property>
  13. <property name="dialect">
  14. org.hibernate.dialect.MySQLDialect
  15. </property>
  16. <property name="show_sql">true</property>
  17. <property name="format_sql">true</property>
  18. <property name="current_session_context_class">thread</property>
  19. <mapping class="bean.StudentBean" />
  20. <mapping class="bean.ClassBean" />
  21. <mapping class="bean.BlobBEAN" />
  22.  
  23. </session-factory>

  spring.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  5. xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context
  15. http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
  16.  
  17. <context:component-scan base-package="service"></context:component-scan> <!-- 自动扫描,把 service包里带有@Component注解的类注册为spring上下问的bean-->
  18.  
  19. <bean id="sessionFactory"
  20. class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  21. <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 在spring中加载hiberntae的配置 -->
  22. </bean>
  23.  
  24. </beans>
    1. StudentService .java 测试在spring中通过DI方式注入SessionFactory
  1. package service;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.stereotype.Service;
  11.  
  12. import bean.StudentBean;
  13.  
  14. @Component("studentService")
  15. public class StudentService {
  16.  
  17. @Autowired
  18. private SessionFactory sessionFactory;
  19.  
  20. public void save(){
  21.  
  22. Session session=null;
  23. Transaction tran=null;
  24.  
  25. try {
  26. session=sessionFactory.getCurrentSession();
  27. tran=session.beginTransaction();
  28. StudentBean stu=new StudentBean();
  29. stu.setStuId(3);
  30. stu.setClassId("3");
  31. stu.setStuName("admin3");
  32. session.save(stu);
  33.  
  34. tran.commit();
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. tran.rollback();
  38. }finally{
  39. //getCurrentSession无须手动关闭
  40. }
  41.  
  42. }
  43.  
  44. /**
  45. * 测试在spring中通过DI方式注入SessionFactory
       * 本类的save方法的事务是由Hibernate管理的,所以要在hibernate配置文件的设置
       * <property name="current_session_context_class">thread</property>
  46. * @param args
  47. */
  48. public static void main(String[] args) {
  49. ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
  50. StudentService stuService=(StudentService)context.getBean("studentService");
  51. stuService.save();
  52. }
  53.  
  54. }
  • Test_Transaction.java测试在spring管理事务。(Hibernate不再参与事务的提交与回滚)
  1. package test;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. import org.springframework.stereotype.Controller;
  7.  
  8. import service.TransactionService;
  9.  
  10. /**
  11. * 测试在spring管理事务。(Hibernate不再参与事务的提交与回滚)
  12. * @author 半颗柠檬、
  13. *
  14. */
  15.  
  16. @Controller(value="tranTest")
  17. public class Test_Transaction {
  18.  
  19. @Autowired
  20. private TransactionService tranService;
  21.  
  22. public static void main(String[] args) throws Exception {
  23. ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
  24.  
  25. Test_Transaction stuTest=(Test_Transaction)context.getBean("tranTest");
  26. stuTest.tranService.save_a();
  27.  
  28. }
  29. }
  • TransactionService .java
  1. package service;
  2.  
  3. import javax.transaction.Transactional;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import dao.StudentDao;
  9.  
  10. @Service
  11. @Transactional
  12. public class TransactionService {
  13. @Autowired
  14. private StudentDao stuDao;
  15.  
  16. public void save_a() throws Exception{
  17. stuDao.save_1();
  18. stuDao.save_2();
  19.  
  20. }
  21.  
  22. }
    1. StudentDao .java
  1. package dao;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Repository;
  7.  
  8. import bean.StudentBean;
  9.  
  10. @Repository(value = "stuDao")
  11. public class StudentDao {
  12.  
  13. @Autowired
  14. private SessionFactory sessionFactory;
  15.  
  16. public void save_1() throws Exception {
  17. Session session = null;
  18.  
  19. try {
  20. session = sessionFactory.getCurrentSession();
  21. StudentBean stu = new StudentBean();
  22. stu.setStuId(15);
  23. stu.setClassId("3");
  24. stu.setStuName("admin3");
  25. session.save(stu);
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. throw new RuntimeException(e);
  29. }
  30.  
  31. }
  32.  
  33. public void save_2() throws Exception {
  34. Session session = null;
  35. try {
  36.  
  37. session = sessionFactory.getCurrentSession();
  38. StudentBean stu = new StudentBean();
  39. stu.setStuId(1);
  40. stu.setClassId("3");
  41. stu.setStuName("admin3");
  42. session.save(stu);
  43.  
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. throw new RuntimeException(e);
  47. }
  48.  
  49. }
  50.  
  51. }
  • spring.xml修改为如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  5. xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context
  15. http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
  16.  
  17. <context:component-scan base-package="service"></context:component-scan> <!-- 自动扫描,把 service包里带有@Component注解的类注册为spring上下问的bean -->
  18. <context:component-scan base-package="dao"></context:component-scan>
  19. <context:component-scan base-package="test"></context:component-scan>
  20.  
  21. <bean id="sessionFactory"
  22. class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  23. <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 在spring中加载hiberntae的配置 -->
  24. </bean>
  25.  
  26. <bean id="dataSource"
  27. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  28. <constructor-arg index="0" name="url"
  29. value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
  30. <constructor-arg index="1" name="username" value="root"></constructor-arg>
  31. <constructor-arg index="2" name="password" value=""></constructor-arg>
  32. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  33. </bean>
  34.  
  35. <!-- 第一种方式:使用xml配置来配置声明式事务 -->
  36. <bean name="transactionManager"
  37. class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  38. <property name="dataSource" ref="dataSource"></property>
  39. <property name="sessionFactory" ref="sessionFactory"></property>
  40. </bean>
  41.  
  42. <tx:advice id="advice_1" transaction-manager="transactionManager">
  43. <tx:attributes>
  44. <tx:method name="save*" propagation="REQUIRED" />
  45. <tx:method name="*" propagation="SUPPORTS" />
  46. </tx:attributes>
  47. </tx:advice>
  48.  
  49. <aop:config>
  50. <!-- Pointcut 是指那些方法需要被执行"AOP",是由"Pointcut Expression"来描述的. -->
  51. <aop:pointcut expression="execution(* service.*.*(..))"
  52. id="point_1" />
  53. <aop:advisor advice-ref="advice_1" pointcut-ref="point_1" />
  54. </aop:config>
  55.  
  56. <!-- 第一种方式结束 -->
  57.  
  58. <!-- 第二种方式:使用事务注解来配置声明式事务 -->
  59.  
  60. <bean name="transactionManager"
  61. class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  62. <property name="dataSource" ref="dataSource"></property>
  63. <property name="sessionFactory" ref="sessionFactory"></property>
  64. </bean>
  65. <tx:annotation-driven transaction-manager="transactionManager" />
  66.  
  67. <!-- 第二种方式结束 -->
  68.  
  69. </beans>
  • hibernate.cfg.xml修改如下:
  1. <?xml version='1.0' encoding='UTF-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <!-- Generated by MyEclipse Hibernate Tools. -->
  6. <hibernate-configuration>
  7.  
  8. <session-factory>
  9. <property name="myeclipse.connection.profile">
  10. com.jdbc.mysql.Driver
  11. </property>
  12. <property name="connection.url">
  13. jdbc:mysql://127.0.0.1:3306/test
  14. </property>
  15. <property name="connection.username">root</property>
  16. <property name="connection.password"></property>
  17. <property name="connection.driver_class">
  18. com.p6spy.engine.spy.P6SpyDriver
  19. </property>
  20. <property name="dialect">
  21. org.hibernate.dialect.MySQLDialect
  22. </property>
  23. <property name="show_sql">true</property>
  24. <property name="format_sql">true</property>
  25. <property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
  26. <mapping class="bean.StudentBean" />
  27. <mapping class="bean.ClassBean" />
  28. <mapping class="bean.BlobBEAN" />
  29.  
  30. </session-factory>
  31.  
  32. </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. 每天一个linux命令:top命令

    top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器.下面详细介绍它的使用方法.top是一个动态显示过程,即可以通过用户按键来不断刷新 ...

  2. python文件导出exe可执行程序

    开门见山的说: 1.安装pyinstaller.(windows 用pip3 Mac 用pip)在cmd中输入:pip3 install pyinstaller 2.找到你要打包的文件的目录的上一个目 ...

  3. 多线程-Thread和ThreadPool

    多线程原理 多线程都是基于委托的. 多线程优缺点 缺点: 1.导致程序复杂,开发调试维护困难,特别是线程交互. 2.线程过多导致服务器卡死,因为占用CPU 内存等资源. 优点: 1.良好的交互,特别对 ...

  4. RVS PA-1800 功放参数

        RVS PA-1800大功率功放技术参数:     文章来源:外星人来地球 欢迎关注,有问题一起学习欢迎留言.评论

  5. python 设计模式之解释器(Interpreter)模式

    #写在前面 关于解释器模式,我在网上转了两三圈,心中有了那么一点概念 ,也不知道自己理解的是对还是错. 其实关于每一种设计模式,我总想找出一个答案,那就是为什么要用这种设计模式, 如果不用会怎么样,会 ...

  6. osg MatrixManipulator CameraManipulator

    <osgGA/MatrixManipulator>:No such file or directory 修改为 #include <osgGA/CameraManipulator&g ...

  7. memcache安装与简单介绍

    本文参考自菜鸟教程中的内容. 安装 安装memcache的时候,请切换为root用户 root@centos # wget http://www.memcached.org/files/memcach ...

  8. Mysql安装、查看密码、修改密码、初始化、修改字符类型

    安装mysql 参照python篇一键安装lnmp.安装完之后再按照下面修改密码,修改配置文件,否则安装的时候就修改配置文件会出错. 注意:这也是二进制安装mysql.另一种二进制安装容易出错,生产环 ...

  9. javascript——URI的编解码方法

    有效的URI(统一资源标示符)是不能包含某些字符的,如空格,所以需要进行编码,编码方法有:encodeURI()和encodeURIComponent(), 对编的码进行解码方法有:decodeURI ...

  10. 【leetcode_easy】598. Range Addition II

    problem 598. Range Addition II 题意: 第一感觉就是最小的行和列的乘积即是最后结果. class Solution { public: int maxCount(int ...