Spring与Struts2整合的目的:

让Spring管理Action

Spring整合Hinernate的目的:

--管理SessionFactory(单例的),数据源

--声明式事务管理

1.首先建一个java项目接可以了

单独加Hibernate的开发环境jar包和配置文件(hibernate.cfg.xml和xxx.hbm.xml)

hibernate.cfg.xml里面包含三类信息:数据库连接信息,其他信息,映射信息(这是未整合时的情况)

public class User {
    private Integer id;
    private String name;
    private Integer age;

    public User() {

    }

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = 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"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.winner.entity">

    <class name="User" table="t_user">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <property name="age"/>
    </class>

</hibernate-mapping>

hibernate.cfg.xml

<!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>
        <!-- 1,数据库连接信息 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="connection.url">jdbc:mysql:///sh</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- 2,其他配置 -->
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

        <!-- 3,导入映射配置 -->
        <mapping resource="com/winner/entity/User.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

单独加Spring的开发环境:jar包和配置文件applicationContext.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:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">
</beans>

下面开始整合,

一、整合的第一步

让Spring容器管理SessionFactory.

方法一:不建议,应该使用专业 的数据库连接池

<!-- 配置SessionFactory,方式一:指定hibernate主配置文件的路径 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>

方法二:建议,这种情况下不需要hibernate.cfg.xml文件了

数据源里面没有方言,需要在hibernateProperties里面配

<?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:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">

    <!-- 加载外部的配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置数据库连接池 ComboPooledDataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 基本的连接信息 -->
        <property name="jdbcUrl" value="${jdbcUrl}"/>
        <property name="driverClass" value="${driverClass}"/>
        <property name="user" value="${username}"/>
        <property name="password" value="${password}"/>
        <!-- 一些管理的配置 -->
        <property name="initialPoolSize" value="3"></property>
        <property name="minPoolSize" value="3"></property>
        <property name="maxPoolSize" value="5"></property>
        <property name="acquireIncrement" value="3"></property>
        <property name="maxIdleTime" value="1800"></property>
    </bean>

    <!-- 配置SessionFactory,不使用Hibernate主配置文件,在这里写所有的Hibernate配置,这样就不需要hibernate的配置文件了-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!--hibernate的数据库连接信息-->
        <property name="dataSource" ref="dataSource"/>
        <!--hibernate其他配置-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql" >true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <!--映射配置-->
        <property name="mappingLocations">
            <list>
                <!--可以有多个-->
                <value>classpath:com/winner/entity/User.hbm.xml</value>
            </list>
        </property>
    </bean>
</beans>

其实下面这种方式其实也挺好的

<!-- 配置SessionFactory,方式三:结合使用 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>

在这种情况下,像上面的xx.hbm.xml映射文件,show_sql等属性都可以保留在hibernate,cfg.xml文件中。

测试

public class SpringTest {

    private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

    @Test
    public void testSessionFactory() {
        SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
        System.out.println(sessionFactory);
    }
}

二、整合的第二步

配置声明式事务管理

<!-- 二、配置声明式事务管理,采用基于注解的方式 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <!--管理事务肯定离不开session,进而需要sessionFactory-->
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

测试事务是否起作用

--能不能正常提交

@Service
public class UserService {

    @Resource
    private SessionFactory sessionFactory;

    @Transactional
    public void saveTwoUsers() {
        Session session = sessionFactory.getCurrentSession();
        session.save(new User());
        session.save(new User());

    }
}
// 测试事务
@Test
public void testTransaction() throws Exception {
    UserService userService = (UserService) ac.getBean("userService");
    userService.saveTwoUsers();
}
Hibernate: insert into t_user (name, age) values (?, ?)
Hibernate: insert into t_user (name, age) values (?, ?)

--有异常能不能回滚

@Service
public class UserService {

    @Resource
    private SessionFactory sessionFactory;

    @Transactional
    public void saveTwoUsers() {
        Session session = sessionFactory.getCurrentSession();
        session.save(new User());
        int i = 1 / 0;
        session.save(new User());

    }
}
Hibernate: insert into t_user (name, age) values (?, ?)
java.lang.ArithmeticException: / by zero

将异常语句去掉,在执行一次

看数据库

第三条被回滚掉了。

Spring与Hibernate整合的更多相关文章

  1. 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)

    轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...

  2. Spring与Hibernate整合,实现Hibernate事务管理

    1.所需的jar包 连接池/数据库驱动包 Hibernate相关jar Spring 核心包(5个) Spring aop 包(4个) spring-orm-3.2.5.RELEASE.jar     ...

  3. Spring与Hibernate整合中,使用OpenSessionInViewFilter后出现sessionFactory未注入问题

    近期在知乎看到一句话,保持学习的有一种是你看到了很多其它的牛人,不甘心,真的不甘心. Spring和hibernate整合的时候,jsp页面做展现,发现展现属性出现: org.apache.jaspe ...

  4. 框架篇:Spring+SpringMVC+hibernate整合开发

    前言: 最近闲的蛋疼,搭个框架写成博客记录下来,拉通一下之前所学知识,顺带装一下逼. 话不多说,我们直接步入正题. 准备工作: 1/ IntelliJIDEA的安装配置:jdk/tomcat等..(本 ...

  5. Spring第九篇【Spring与Hibernate整合】

    前言 前面已经学习了如何使用Spring与Struts2进行整合,本博文主要讲解如何使用Spring对Hibernate进行整合 Spring和Hibernate整合的关键点: SessionFact ...

  6. spring+springmvc+hibernate 整合

    三大框架反反复复搭了很多次,虽然每次都能搭起来,但是效率不高.最近重新搭了一次,理顺了思路,整理了需要注意的地方,分享出来. 工具:Eclipse(jdk 1.7) spring和hibernate版 ...

  7. spring和hibernate整合,事务管理

    一.spring和hibernate整合开发步骤 1 引入jar文件,用户libarary列表如下 //spring_core spring3..9core\commons-logging-1.2.j ...

  8. spring和hibernate整合时报sessionFactory无法获取默认Bean Validation factory

    Hibernate 3.6以上版本在用junit测试时会提示错误: Unable to get the default Bean Validation factory spring和hibernate ...

  9. spring+springmvc+hibernate整合遇到的问题

    spring+springmvc+hibernate整合遇到的问题2016年10月20日 23:24:03 守望dfdfdf 阅读数:702 标签: ssh学习经历的异常exception异常框架更多 ...

  10. Java进阶知识25 Spring与Hibernate整合到一起

    1.概述 1.1.Spring与Hibernate整合关键点 1) Hibernate的SessionFactory对象交给Spring创建.    2) hibernate事务交给spring的声明 ...

随机推荐

  1. 如果在配置中将“system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled”设置为 true,则需要终结点指定相对地址。如果在终结点上指定相对侦听 URI,则该地址可以是绝对地址。若要解决此问题,请为终结点“http://localhost/Service1.svc”指定相对 URI。

    问题: 如果在配置中将"system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled"设置为 ...

  2. 新手自学ABAP(1)--数据类型

    一.DATA语句 1.TYPE type ex:  可以利用冒号声明多个变量. DATA : gv_num1 TYPE I,   gv_num2 TYPE I. 2.LIKE num   (num可以 ...

  3. LeapMotion(2):追踪五指

    上一篇文章,我们实现了Leap Motion的简单测试.追踪其中一个手指并用红色圆形表示其在空间的位置. 这篇文章,我们来实现五指的追踪. 其实,能够实现一指的追踪,那么五指的追踪自然不成问题.但是, ...

  4. MinGW-64 安装

    一.在mingw-w64官网下载mingw-w64在线安装包 二.点击mingw-w64进行安装,选择: Version:选最新版本 我这个是4.9.2 Architecture:x86_64 (64 ...

  5. 【UIScrollView】基本方法+基本描述

    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(, , , )]; scrollView.backgroundColor = [ ...

  6. try-catch-finally中return的执行情况分析

    try-catch-finally中return的执行情况分析: 1.在try中没有异常的情况下try.catch.finally的执行顺序 try --- finally 2.如果try中有异常,执 ...

  7. Careercup - Facebook面试题 - 5671785349513216

    2014-05-02 01:05 题目链接 原题: bool anaStrStr (string needle, string haystack) { } Write a function that ...

  8. Http之Get/Post请求区别

    Http之Get/Post请求区别 1.HTTP请求格式: <request line> <headers> <blank line> [<request-b ...

  9. mysql merge

    merge 是一组 myisam 表的组合, 锁住一个 merge 表它会吧底下所有的表全给锁住. 创建只读表 )) engine = merge union (t1,t2); 创建可插入的表, (以 ...

  10. springMVC 简单事例

    本帖最后由 悲观主义者一枚 于 2015-1-31 17:55 编辑 使用SpringMvc开发Android WebService入门教程1.首先大家先创建一个JavaWeb项目2.然后加入Spri ...