1.拷贝我们的spring事务控制所需的jar包

2.在spring容器中配置我们的hibernateTemplate以及事务管理器 

  <?xml version="1.0" encoding="UTF-8"?>
  <!-- spring的配置文件:导入约束 -->
  <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
    ">
    <!-- 自定义的java对象交给spring进行管理 -->
    <bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl">
      <property name="customerDao" ref="customerDao"></property>
    </bean>
    <bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
      <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>
    <!-- 第三方的jar包中的java对象交给spring进行管理 -->
    <!-- 创建一个hibernateTemplate对象 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
      <!-- 注入sessionFactory -->
      <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 创建sessionFactory对象 -->
    <!-- 当spring和hibernate整合时,这个sessionFactory的实现类是由spring提供的:LocalSessionFactoryBean,
    创建sessionFactory是根据hibernate的核心配置文件
    -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>
    <!--配置hibernate的事务管理 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 配置事务管理通知 -->
    <tx:advice id="txAdvice">
      <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" read-only="false"/>
        <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
      </tx:attributes>
    </tx:advice>
    <!-- 配置事务的AOP -->
    <aop:config>
      <aop:pointcut expression="execution(* com.itheima.service.impl.*.* (..))" id="pt"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>
</beans>

3.对我们的到层进行改造

  public interface CustomerDao {
    void save(Customer customer);

    List<Customer> find();
  }

  public class CustomerDaoImpl implements CustomerDao {
    /**
    * 通过sessionFactory创建session对象进行数据库的CRUD操作
    * 创建HiberanteTemplete的对象过程中,需要依赖注入一个sessionFactory
    */
    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
      this.hibernateTemplate = hibernateTemplate;
    }
    public void save(Customer customer) {
      hibernateTemplate.save(customer);
    }

    public List<Customer> find() {
      //hql查询所有的客户
      //1.获取query对象,session.createQuery(hql) 2.传递查询参数 3.得到查询 结果
      //find方法第一个参数,hql语句,第二个参数,变长参数列表
      return (List<Customer>) hibernateTemplate.find("from Customer");
    }

  }

4.测试我们的hibernate和spring整合

  @RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(locations={"classpath:applicationContext.xml"})
  public class SpringAndHibernateTest {
    @Autowired
    private CustomerService customerService;

    @Test
    public void getAllCustomerTest(){
      List<Customer> customers = customerService.getAllCustomer();
      for (Customer customer : customers) {
        System.out.println(customer);
      }
    }
    @Test
    public void addCustomerTest(){
      Customer customer = new Customer();
      customer.setCustName("赵子龙");
      customerService.addCustomer(customer);
    }
  }

这里我们测试我们的fgetAllCustomerTest方法会报错,具体原因呢,我也说不清楚,但可以看看这个链接https://blog.csdn.net/yinjian520/article/details/866669,

  org.springframework.orm.hibernate5.HibernateSystemException: createQuery is not valid without active transaction; nested exception is org.hibernate.HibernateException:   createQuery is not valid without active transaction
  at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:219)
  at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:344)
  at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:309)
  at org.springframework.orm.hibernate5.HibernateTemplate.find(HibernateTemplate.java:863)
  at com.itheima.dao.impl.CustomerDaoImpl.find(CustomerDaoImpl.java:25)
  at com.itheima.service.impl.CustomerServiceImpl.getAllCustomer(CustomerServiceImpl.java:18)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
  at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
  at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
  at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
  at com.sun.proxy.$Proxy33.getAllCustomer(Unknown Source)
  at com.itheima.test.SpringAndHibernateTest.getAllCustomerTest(SpringAndHibernateTest.java:23)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
  at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
  at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
  at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
  at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
  Caused by: org.hibernate.HibernateException: createQuery is not valid without active transaction
  at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:334)
  at com.sun.proxy.$Proxy34.createQuery(Unknown Source)
  at org.springframework.orm.hibernate5.HibernateTemplate$29.doInHibernate(HibernateTemplate.java:866)
  at org.springframework.orm.hibernate5.HibernateTemplate$29.doInHibernate(HibernateTemplate.java:863)
  at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:341)
  ... 49 more

解决的方法就是在hibernate的核心配置文件中注释

  <?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql:///ssh_280</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">root</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      <!-- 配置C3P0连接池 -->
      <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
      <property name="hibernate.hbm2ddl.auto">update</property>

      <!-- 显示sql语句 show_sql true|false(默认值) -->
      <property name="hibernate.show_sql">true</property>

      <!-- 格式化sql format_sql true|false(默认值) -->
      <property name="hibernate.format_sql">true</property>

      <!-- 获取与当前线程绑定的session
      当spring和hibernate整合的时候,获取的session对象本身就是与当前线程绑定的对象
      所以hibernate.current_session_context_class的配置可以省略
      * session对象是由spring提供的session,这个session并不认识thread的配置
      * 需要配置SpringSessionContext
      <property name="hibernate.current_session_context_class">SpringSessionContext</property>
      -->
      <!-- 映射文件的位置
        class:指定配置了jpa注解的实体类的全限定类名
        resource:xml格式的映射文件
      -->
      <mapping resource="com/itheima/entity/Customer.hbm.xml" />
    </session-factory>
  </hibernate-configuration>

  看一下我们测试以后的结果吧

  每天进步一点点!

 

ssh整合之三hibernate和spring整合的更多相关文章

  1. struts2,hibernate,spring整合笔记(2)

    上一话struts2,hibernate,spring整合笔记(1) 接下来继续 配置完struts之后就要开始hibernate的配置 hibernate的环境并不依赖web开发环境,在我第一次配置 ...

  2. struts2,hibernate,spring整合笔记(3)

    struts2,hibernate,spring整合笔记(1) struts2,hibernate,spring整合笔记(2) 配好struts和hibernate就要开始spring了 老规矩,还是 ...

  3. Hibernate 与Spring整合出现 hibernate.HibernateException: createCriteria is not valid without active transaction

    当 Hibernate 和 Spring 整合时,在 Spring 中指定的 Hibernate.cfg.xml 文件内容中要注释掉以下内容: <!-- Enable Hibernate's a ...

  4. 【SSH框架】系列之 Spring 整合 Hibernate 框架

    1.SSH 三大框架整合原理 Spring 与 Struts2 的整合就是将 Action 对象交给 Spring 容器来负责创建. Spring 与 Hibernate 的整合就是将 Session ...

  5. 从0开始整合SSM框架--2.spring整合mybatis

    依赖:<properties> <!-- spring版本号 --> <spring.version>4.1.3.RELEASE</spring.versio ...

  6. SSH开发实践part4:Spring整合Struts

    1 好了,前面spring与hibernate的整合开发我们基本上讲完了,现在要开始服务层的开发,也就是处理事务的action,在这里我们需要引入spring与struts的整合.也就是将action ...

  7. ssh整合之五struts和spring整合

    1.首先,我们需要先分析一下,我们的spring容器在web环境中,只需要一份就可以了 另外,就是我们的spring容器,要在我们tomcat启动的时候就创建好了(包括其中的spring的对象),怎么 ...

  8. 框架整合----------Hibernate、spring整合

    说到整合框架,其实也就是环境的搭建了,首先我们要导包,这里连接数据库我们用到了spring容器,我们用连接池来进行数据库的连接,我们需要导入c3p0和jdbc的jar包,其余的就是spring和Hib ...

  9. struts2,hibernate,spring整合笔记(4)--struts与spring的整合

    饭要一口一口吃,程序也要一步一步写, 很多看起来很复杂的东西最初都是很简单的 下面要整合struts和spring spring就是我们的管家,原来我们费事费神的问题统统扔给她就好了 先写一个测试方法 ...

随机推荐

  1. CentOS7.4安装MySQL踩坑记录

    CentOS7.4安装MySQL踩坑记录 time: 2018.3.19 CentOS7.4安装MySQL时网上的文档虽然多但是不靠谱的也多, 可能因为版本与时间的问题, 所以记录下自己踩坑的过程, ...

  2. Facebook兆级别图片存储及每秒百万级别图片查询原理

    前言 Facebook(后面简称fb)是世界最大的社交平台,需要存储的数据时刻都在不断剧增(占比最大为图片,每天存储约20亿张,大概是微信的三倍). 那么问题来了,fb是如何存储兆级别的图片?并且又是 ...

  3. js获取元素的滚动高度,和距离顶部的高度

    jq: 获取浏览器显示区域(可视区域)的高度 : $(window).height(); 获取浏览器显示区域(可视区域)的宽度 : $(window).width(); 获取页面的文档高度 $(doc ...

  4. Linux上部署SVN

    Linux上部署SVN author:headsen chen  2017-10-16  16:45:04 前提:通过yum来安装,必须是centos6.5的桌面版的.否则会出现某些的安装包不全而导致 ...

  5. CSS Grid 网格布局全解析

    介绍 CSS Grid(网格) 布局使我们能够比以往任何时候都可以更灵活构建和控制自定义网格. Grid(网格) 布局使我们能够将网页分成具有简单属性的行和列.它还能使我们在不改变任何HTML的情况下 ...

  6. 基于 CDH 构建推荐系统

    我理解的推荐系统本质是一种排序方式.排序的规则是按照我们预测的用户喜好程度的一个排序的列表,而如何定义用户的喜好程度是推荐系统要解决的核心问题.机器学习的算法只是推荐系统的一部分.构建一个完整的推荐系 ...

  7. sklearn包中有哪些数据集你都知道吗?

    注册了博客园一晃有3个月了,同时接触机器学习也断断续续的算是有1个月了.今天就用机器学习神器sklearn包的相关内容作为我的开篇文章吧. 本文将对sklearn包中的数据集做一个系统介绍,并简单说一 ...

  8. java排序算法(八):希尔排序(shell排序)

    java排序算法(八):希尔排序(shell排序) 希尔排序(缩小增量法)属于插入类排序,由shell提出,希尔排序对直接插入排序进行了简单的改进,它通过加大插入排序中元素之间的间隔,并在这些有间隔的 ...

  9. 浅谈-RMQ

    浅谈RMQ Today,我get到了一个新算法,开心....RMQ. 今天主要说一下RMQ里的ST算法(Sparse Table). RMQ(Range Minimum/Maximum Query), ...

  10. CSS奇思妙想图形(心形、气泡三角形、切角、梯形、饼图等)

    今天看到一篇不错文章,在原来CSS3图形创建基础上扩展了很多. 这里记录总结下 心形 原理:利用 圆形 和 正方形实现 HTML: <div class="heartShaped&qu ...