(十七)Hibnernate 和 Spring 整合

一、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>



全部代码在: 链接

时间: 2024-08-25 19:41:42

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

springMVC+MyBatis+Spring 整合(3)

spring mvc 与mybatis 的整合. 加入配置文件: spring-mybaits.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" xm

Spring整合Struts2

Spring整合Struts21整合目的:让Spring的IOC容器去管理Struts2的Action, 2Struts2是web开源框架,Spring要整合Struts2,也就是说要在web应用使用Spring①. 需要额外加入的 jar 包:spring-web-4.0.0.RELEASE.jarspring-webmvc-4.0.0.RELEASE.jar ②. Spring 的配置文件, 和非 WEB 环境没有什么不同 ③. 需要在 web.xml 文件中加入如下配置: <!-- 配置

Spring整合hibernate4:事务管理

Spring和Hibernate整合后,通过Hibernate API进行数据库操作时发现每次都要opensession,close,beginTransaction,commit,这些都是重复的工作,我们可以把事务管理部分交给spring框架完成. 配置事务(xml方式) 使用spring管理事务后在dao中不再需要调用beginTransaction和commit,也不需要调用session.close(),使用API  sessionFactory.getCurrentSession()来

springMVC+MyBatis+Spring 整合(4) ---解决Spring MVC 对AOP不起作用的问题

解决Spring MVC 对AOP不起作用的问题 分类: SpringMVC3x+Spring3x+MyBatis3x myibaits spring J2EE2013-11-21 11:22 640人阅读 评论(1) 收藏 举报 用的是 SSM3的框架 Spring MVC 3.1 + Spring 3.1 + Mybatis3.1第一种情况:Spring MVC 和 Spring 整合的时候,SpringMVC的springmvc.xml文件中 配置扫描包,不要包含 service的注解,S

Spring整合MyBatis

首先下载jar包  mybatis-spring.jar 原因spring3.0出来的早,MyBatis3.0晚,意味着Spring不愿意去在一个没有做出发布版本的MyBatis上做过多的设置.所以,最终jar包提供者第三方. <!--Mybatis+Spring整合--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId&g

JMS 之 Active MQ 的spring整合

一.与spring整合实现ptp的同步接收消息 pom.xml: <!-- https://mvnrepository.com/artifact/org.springframework/spring-jms --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>4.3.7.RE

8 -- 深入使用Spring -- 7...2 MVC框架与Spring整合的思考

8.7.2 MVC 框架与Spring整合的思考 对于一个基于B/S架构的JAVA EE 应用而言,用户请求总是向MVC框架的控制器请求,而当控制器拦截到用户请求后,必须调用业务逻辑组件来处理用户请求.此时有一个问题:控制器应该如何获得业务逻辑组件? 最容易想到的策略是,直接通过new 关键字创建业务逻辑组件,然后调用业务逻辑组件的方法,根据业务逻辑方法的返回值确定结果. 在实际的应用中,很少见到采用上面的访问策略,因为这是一种非常差的策略.不这样做至少有如下三个原因: ⊙ 控制器直接创建业务逻

Spring整合strus2简单应用总结

本身strus2没接触过,所以这块学的一知半解,正常不整合的还没学(接着学) step: 1.创建web工程 2.在/WEB-INF/lib引入jar包 asm-3.3.jarasm-commons-3.3.jarasm-tree-3.3.jarcom.springsource.net.sf.cglib-2.2.0.jarcom.springsource.org.aopalliance-1.0.0.jarcom.springsource.org.aspectj.weaver-1.6.8.RELE

Spring整合jdbc

首先web.xml文件跟往常一样,加载spring容器和加载org.springframework.web.context.ContextLoaderListener读取applicationContext.xml文件初进行始化. 使用spring整合jdbc工具步骤: 1.使用连接池com.mchange.v2.c3p0.ComboPooledDataSource等工具创建数据源. 2.把数据源交给LazyConnectionDataSourceProxy进行管理 3.把LazyConnect