一、Springl为什么要整合Hibernate
 
二者的整合主要是把hibernate中核心的一些类型交给spring管理,这些类型主要包括sessionFactory、
transactionManager、transactionTemplate,把这些类型配置成bean,然后注入到hibernate的DAO层
中,这样在DAO层中就可以直接使用这些对象而不用考虑如何创建这些对象
最主要的还是对Service层(业务逻辑层)的事务控制。这个为整合hibernate而创建的spring配置文件可以是任意名称(一般命名为applicationContext.xml),可以存放在任意位置(可以在classes目录),只要Spring能够正确加载该文件即可。

#### 
########  
##########################    
##############

 其实hibernate.cfg.xml文件主要配置的都是sessionFactory的信息,为了便于管理,建议不需要全部把Hibernate.cfg.xml的全部信息转移到spring的配置文件中,只需要把连接数据库的信息交给spring装配成数据源(DBCP数据源或者C3P0等)datasourse(因为DataSourceTransactionManager事务管理器需要这个参数),然后再装配sessionFactory的时候,引入hibernate.cfg.xml即可。如:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource"
 
       
p:configLocation="classpath:hibernate.cfg.xml"
/>

#### 
########  
##########################    
#############
二、整合步骤
  
步骤一、装配LocalSessionFactoryBean

       
在Spring提供的org.springframework.orm.hibernate3.LocalSessionFactoryBean中进行整合,这个Bean提供了多种整合的方法:

方法1.可以通过<property
name="hibernateProperties">标签将hibernate的配置信息以property的方式写入.

<property
name="hibernateProperties">
            
<props>
                
<prop
key="hibernate.dialet">org.hibernate.dialect.MySQLDialect</prop>

<prop
key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>

<prop
key="hibernate.connection.url">jdbc:mysql://localhost:3306/book</prop>

<prop
key="hibernate.connection.username">yuan</prop>

<prop
key="hibernate.connection.password">hanyuan9113</prop>

<prop
key="hibernate.show_sql">true</prop>

<prop
key="hibernate.connection.autocommit">true</prop>

</props>
        
</property>

   
方法2.可以通过<property
name="configLocation">标签直接读取hibernate.cfg.xml配置信息

<property
name="configLocation">
            
<value>classpath:hibernate.cfg.xml</value>

  </property>
       
#上面的这种配置可能出现错误,你可以使用下面的配置解决:

<bean id="sessionFactory"
  
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

  
p:configLocation="classpath:hibernate.cfg.xml"

/>

 方法3.可以通过<property
name="dataSource">标签指定连接池,连接池中有连接数据库的信息

      
<property name="dataSource">
            
<ref bean="myDataSource" />
       
</property>
      
或者也可以这样写:
  <bean
id="sessionFactory"   
   
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource"  
/>

用以上三种方法之一配置Hibernate信息,装配LocalSessionFactoryBean:

<bean id="sessionFactory"
        
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property
name="hibernateProperties">
            
<props>

<!-- 指定数据库方言:MySql
-->
                 
<prop
key="hibernate.dialet">org.hibernate.dialect.MySQLDialect</prop>

<prop
key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>

<prop
key="hibernate.connection.url">jdbc:mysql://localhost:3306/book</prop>

<prop
key="hibernate.connection.username">yuan</prop>

<prop
key="hibernate.connection.password">hanyuan9113</prop>

<prop
key="hibernate.show_sql">true</prop>

<prop
key="hibernate.connection.autocommit">true</prop>

</props>
        
</property>
 
        
<property
name="mappingResources">
            
<list>
                
<value>com/sunflower/entity/Sutdent.hbm.xml</value>

</list>
        
</property>
 </bean>
 其中<property
name="mappingResources">属性是配置映射文件的。如果有很多映射文件要配置,用这种方法就要为每个映射文件书写配置信息,
这样将会非常麻烦。Spring的
org.springframework.orm.hibernate3.LocalSessionFactoryBean提供了一
个<property
name="mappingDirectoryLocations">属性,将所有配置文件放置到一个统一的地方就能一次性进行配置。例如:

<property
name="mappingDirectoryLocations">
            
<list>
                
<value>classpath:com/sunflower/entity</value>

</list>
       
</property>

将一次性配置com.sunflower.entity包下的所有映射文件。

 
步骤二:装配org.springframework.orm.hibernate3.HibernateTemplate

<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">

<property
name="sessionFactory">
            
<ref bean="sessionFactory" />
        
</property>
    
</bean>
HibernateTemplate类是Spring提供给我们进行Hibernate持久层操作的类,它对增删查改方法进行了封装,通过这个类我们很方便就能操作数据库。<property
name="sessionFactory">标签配置LocalSessionFactoryBean

 
步骤三:装配自定义DAO

   <bean
id="studentDao"
class="com.sunflower.daoimp.StudentDaoImp">
        
<property
name="hibernateTemplate">
            
<ref bean="hibernateTemplate"
/>
        
</property>
    
</bean>
为每个Dao的实现类配置一个HibernateTemplate,然后在Spring配置文件中进行装配,这样就可以使用这个HibernateTemplate进行持久层的操作了。

StudentDaoImp.java

public class StudentDaoImp
extends StudentDaoAdapter {
    
@Override
    
public void saveStudent(Student student) {
        
this.hibernateTemplate.save(student);
    
}
 
    
@Override
    
public Student getStudent(Student student) {
        
return this.hibernateTemplate.get(Student.class,
student.getSno());
    
}
 }

进行测试,Test.java:

public class Test {
 
    
@org.junit.Test
    
public void saveStudent() {
        
ApplicationContext context = new
ClassPathXmlApplicationContext(
                
"applicationContext.xml");
        
StudentDao studentDao = (StudentDao)
context.getBean("studentDao");
 
        
Student student = new Student();
 
        
student.setCno(4);
        
student.setName("喜爱啸");
        
student.setScore(70);
 
        
studentDao.saveStudent(student);
 
    
}
 
 //   
@org.junit.Test
    
public void getStudent() {
        
ApplicationContext context = new
ClassPathXmlApplicationContext(
                
"applicationContext.xml");
        
StudentDao studentDao = (StudentDao)
context.getBean("studentDao");
 
        
Student student = new Student();
        
student.setSno(15);
        
Student s = studentDao.getStudent(student);
 
        
System.out.println("name:" + s.getName());
    
}
 
 }
------------------------------------------------------------------

这里有一个比较全的spring整合Hibernate后的spring配置文件,可以作为参考:
<?xml version="1.0"
encoding="UTF-8"?>
<!-- 指定Spring配置文件的Schema信息 -->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
   
<!-- 定义数据源Bean,使用C3P0数据源实现 -->
   
<bean id="dataSource"

class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
   
   
<!-- 指定连接数据库的驱动 -->
   
   
<property name="driverClass"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>

<!-- 指定连接数据库的URL -->
   
   
<property name="jdbcUrl"
value="jdbc:sqlserver://localhost;DatabaseName=mydb;SelectMethod=cursor"/>

<!-- 指定连接数据库的用户名 -->
   
   
<property name="user"
value="sa"/>
   
   
<!-- 指定连接数据库的密码 -->
   
   
<property name="password"
value="sa"/>
   
   
<!-- 指定连接数据库连接池的最大连接数 -->
   
   
<property name="maxPoolSize"
value="40"/>
   
   
<!-- 指定连接数据库连接池的最小连接数 -->
   
   
<property name="minPoolSize"
value="1"/>
   
   
<!-- 指定连接数据库连接池的初始化连接数 -->
   
   
<property name="initialPoolSize"
value="1"/>
   
   
<!-- 指定连接数据库连接池的连接的最大空闲时间 -->
   
   
<property name="maxIdleTime"
value="20"/>
   
</bean>
   
<!-- 定义Hibernate的SessionFactory
-->
   <bean
id="sessionFactory"

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<!-- 依赖注入数据源,注入正是上面定义的dataSource
-->
   
   
<property name="dataSource"
ref="dataSource"/>
   
   
<!-- mappingResouces属性用来列出全部映射文件
-->
     
<property
name="mappingResources">
   
   
   
<list>
   
   
   
   
<value>com/etc/model/Leave.hbm.xml</value>

<value>com/etc/model/Traine.hbm.xml</value>

<value>com/etc/model/Train.hbm.xml</value>

</list>
   
   
</property>

<!-- mappingDirectoryLocations属性列出映射文件位置
-->
     <!--<property
name="mappingDirectoryLocations">
       
   
<list>
           
   
<value>classpath*:/hbm</value>

</list>
       
</property>
      
-->
 
 
   
<!-- 定义Hibernate的SessionFactory的属性
-->
   
   
<property
name="hibernateProperties">
   
   
   
<props>
   
   
   
   
<!-- 指定数据库方言:SQLServer -->
   
   
   
   
<prop
key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>

<!-- 指定数据库方言:Oracle
-->
  
   
   
<!--<prop
key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
           
-->    
   
   
 
     
     
    <!--
是否根据需要每次自动创建数据库 -->
   
   
   
   
<prop
key="hibernate.hbm2ddl.auto">none</prop>

<!-- 显示Hibernate持久化操作所生成的SQL
-->
   
   
   
   
<prop
key="hibernate.show_sql">true</prop>

<!-- 将SQL脚本进行格式化后再输出 -->
   
   
   
   
<prop
key="hibernate.format_sql">true</prop>

<prop
key="hibernate.connection.autocommit">true</prop>

</props>
   
   
</property>
   
</bean>

<!--
配置Hibernate的局部事务管理器,使用HibernateTransactionManager类
该类实现PlatformTransactionManager接口,是针对Hibernate的特定实现-->

 
<bean id="transactionManager"

class="org.springframework.orm.hibernate3.HibernateTransactionManager">

<!--
配置HibernateTransactionManager时需要依注入SessionFactory的引用
-->
       
<property
name="sessionFactory">
       
   
<ref bean="sessionFactory" />
   
   
</property>
   
</bean>
   
<bean id="transactionTemplate"

class="org.springframework.transaction.support.TransactionTemplate">

<property
name="transactionManager">
    
   
   
<ref
bean="transactionManager"/>
   
   
</property>
   
</bean>
</beans>

Spring学习7-Spring整合Hibernate的更多相关文章

  1. Spring 学习笔记之整合Hibernate

    Spring和Hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心SQ ...

  2. Spring学习笔记之整合hibernate

    1.web.xml里边要配置好对应的springxml的路径 <context-param> <param-name>contextConfigLocation</par ...

  3. Spring学习(十一)-----Spring使用@Required注解依赖检查

    Spring学习(九)-----Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种 ...

  4. Spring学习(六)-----Spring使用@Autowired注解自动装配

    Spring使用@Autowired注解自动装配 在上一篇 Spring学习(三)-----Spring自动装配Beans示例中,它会匹配当前Spring容器任何bean的属性自动装配.在大多数情况下 ...

  5. Spring学习笔记四 整合SSH

    三大框架架构(整合原理) 步骤1:导包 Hibernate包 1.Hibernate包,hibernate/lib/required 2.hibernate/lib/jpa | java persis ...

  6. spring学习 六 spring与mybatis整合

    在mybatis学习中有两种配置文件 :全局配置文件,映射配置文件.mybatis和spring整合,其实就是把mybatis中的全局配置文件的配置内容都变成一个spring容器的一个bean,让sp ...

  7. Spring学习之Spring与Mybatis的两种整合方式

    本机使用IDEA 2020.1.MySql 8.0.19,通过Maven进行构建 环境准备 导入maven依赖包 <dependencies> <dependency> < ...

  8. spring学习07(整合MyBatis)

    10.整合MyBatis 10.1 相关jar包 junit <dependency> <groupId>junit</groupId> <artifactI ...

  9. spring学习(三) ———— spring事务操作

    前面一篇博文讲解了什么是AOP.学会了写AOP的实现,但是并没有实际运用起来,这一篇博文就算是对AOP技术应用的进阶把,重点是事务的处理. --wh 一.jdbcTemplate 什么是JdbcTem ...

  10. Spring学习【Spring概述】

    从本文開始,我们就要一起学习Spring框架,首先不得不说Spring框架是一个优秀的开源框架. 当中採用IoC原理实现的基于Java Beans的配置管理和AOP的思想都是非常值得学习与使用的.以下 ...

随机推荐

  1. sqlSQL2008如何创建定时作业(代理服务)(转)

    SQL2008如何创建定时作业?此方法也适应于Sql Server2005数据库,有兴趣的可以来看下! 1.打开[SQL Server Management Studio],在[对象资源管理器]列表中 ...

  2. Navi.Soft20.WinCE使用手册

    1.概述 1.1应用场景 随着物联网的普及,越来越多的制造商对货品从原料配备,加工生产,销售出库等环节的要求和把控越来越高.在此情况之下,传统的ERP软件已经无法满足现有的流程. 移动设备的应用,在很 ...

  3. TeeChart控件的安装与常用 功能设置

    TeeChart控件的安装 TeeChart 7.0 With Source在Delphi 7.0中的安装 一.删除Delphi7自带TeeChart  1.Component -> insta ...

  4. Inode详解-重要

    一.inode是什么 理解inode,要从文件储存说起. 文件储存在硬盘上,硬盘的最小存储单位叫做"扇区"(Sector).每个扇区储存512字节(相当于0.5KB). 操作系统读 ...

  5. [转]仿World Wind构造自己的C#版插件框架——WW插件机制精简改造

    很久没自己写东西啦,早该好好总结一下啦!一个大师说过“一个问题不应该被解决两次!”,除了一个好脑筋,再就是要坚持总结. 最近需要搞个系统的插件式框架,我参照World Wind的插件方式构建了个插件框 ...

  6. box-css3

    父容器样式必须有定义:"{ display: -webkit-box }" 现象:水平时只能在一行布局,子容器在垂直方向上会填充父容器. 技巧:可以做水平居中和垂直居中.也可以实现 ...

  7. MemCached配置与缓存知识概述

    先看看百度百科里面对缓存的介绍: 缓存(Cache memory)是硬盘控制器上的一块内存芯片,具有极快的存取速度,它是硬盘内部存储和外界接口之间的缓冲器.由于硬盘的内部数据传输速度和外界介面传输速度 ...

  8. 又折腾到这么晚 , 图片Viewpager PagerIndicator,listview 和侧边栏滑动的事件处理

    代码 思路 根据坐标判断 事件是否拦截 调用 getParent().requestDisallowInterceptTouchEvent(true);方法告诉上层ViewGroup 是否拦截 返回t ...

  9. Yii2-Redis使用小记 - Cache

    前些天简单学习了下 Redis,现在准备在项目上使用它了.我们目前用的是 Yii2 框架,在官网搜索了下 Redis,就发现了yii2-redis这扩展. 安装后使用超简单,打开 common/con ...

  10. [转]细说MySQL Explain和Optimizer Trace简介

    在开发过程中,对每个上线的SQL查询指纹(query figerprint)的质量都应有估算:而估算DB查询质量最直接的方法,就是分析其查询执行计划( Query Execution Plan ,即Q ...