spring 中配置sessionFactory及用法

方法一:

1、在Spring的applicationContext.xml中配置bean

<!-- 启用注解注入  -->
      <context:annotation-config />
      <!-- spring扫描的包 -->
      <context:component-scan base-package="com.iven"/> 
     
      <!-- 配置数据源 -->
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
       <property name="driverClassName" value="com.MySQL.jdbc.Driver" />     
       <property name="url" value="jdbc:mysql://172.25.9.99:3306/fzghc" />
       <property name="username" value="root"></property>
       <property name="password" value="123456"></property>       
      </bean>     
      
       <!-- 配置Spring的SessionFactory -->
      <bean id="sessionFactory"        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="annotatedClasses">
            <list>
                <value>com.iven.entity.User</value>
                <value>com.iven.entity.Repairs</value>
            </list>
        </property>       
        <property name="hibernateProperties">
            <value>
             hibernate.dialect=org.hibernate.dialect.MySQLDialect
    <!-- hibernate.dialect=org.hibernate.dialect.SQLServerDialect -->
    hibernate.show_sql=true    
            </value>
        </property>       
      </bean>
     
      <!-- 添加事务管理 -->
      <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name="sessionFactory" ref="sessionFactory"></property>
      </bean>
     
      <tx:annotation-driven transaction-manager="transactionManager"/>

<!-- 添加事务管理 -->
      
      <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name="sessionFactory" ref="sessionFactory"></property>
      </bean>      
      <tx:annotation-driven transaction-manager="transactionManager"/>    
      
      <bean id="txManager"       class="org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name="sessionFactory" ref="sessionFactory"></property>
      </bean>
      
      <tx:advice  id="txAdvice" transaction-manager="txManager">
         <tx:attributes>
            <!-- all methods starting with 'get' are read-only -->
            <tx:method name="queryByUsername" read-only="true"/>   
            <!-- other methods use the default transaction settings (see below) -->
            <tx:method name="*" />              
          </tx:attributes>
      </tx:advice>
      
      <aop:config>
        <aop:pointcut expression="execution(* com.iven.dao.*.*(..))"           id="fooServiceOperation"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
      </aop:config>

2、添加类BaseSessionFactoryImpl用于获取Session,类BaseSessionFactoryImpl的内容如下:

public class BaseSessionFactoryImpl {

@Resource(name="sessionFactory")
 private SessionFactory sessionFactory=null;
 public Session getSession(){
  return sessionFactory.getCurrentSession();
 }
}

3、在Dao层获取Session,

public class UserDaoImplextends BaseSessionFactoryImpl
{

public User queryByUsername(String userName) {    
     User user=null;
     String sql="select user from User user where user.userName="+userName;
     try {
       user=(User) getSession().get(User.class, 1);   
     } catch (Exception e) {
      e.printStackTrace();
     }     
    return user;
 }

}

4.重点注意事项

SessionFactory的getCurrentSession并不能保证在没有当前Session的情况下会自动创建一个新的,这取决于CurrentSessionContext的实现,SessionFactory将调用CurrentSessionContext的currentSession()方法来获得Session。

在Spring中,如果我们在没有配置TransactionManager并且没有事先调用SessionFactory.openSession()的情况直接调用getCurrentSession(),那么程序将抛出“No
Session found for current thread”异常。

如果配置了TranactionManager并且通过@Transactional或者声明的方式配置的事务边界,那么Spring会在开始事务之前通过AOP的方式为当前线程创建Session,此时调用getCurrentSession()将得到正确结果。

然而,产生以上异常的原因在于Spring提供了自己的CurrentSessionContext实现,如果我们不打算使用Spring,而是自己直接从hibernate.cfg.xml创建SessionFactory,并且为在hibernate.cfg.xml
中设置current_session_context_class为thread,也即使用了ThreadLocalSessionContext,那么我们在调用getCurrentSession()时,如果当前线程没有Session存在,则会创建一个绑定到当前线程。

Hibernate在默认情况下会使用JTASessionContext,Spring提供了自己SpringSessionContext,因此我们不用配置current_session_context_class,当Hibernate与Spring集成时,将使用该SessionContext,故此时调用getCurrentSession()的效果完全依赖于SpringSessionContext的实现。

在没有Spring的情况下使用Hibernate,如果没有在hibernate.cfg.xml中配置current_session_context_class,有没有JTA的话,那么程序将抛出"No
CurrentSessionContext
configured!"异常。此时的解决办法是在hibernate.cfg.xml中将current_session_context_class配置成thread。

在Spring中使用Hibernate,如果我们配置了TransactionManager,那么我们就不应该调用SessionFactory的openSession()来获得Sessioin,因为这样获得的Session并没有被事务管理。

至于解决的办法,可以采用如下方式:
1. 在spring 配置文件中加入

<tx:annotation-driven transaction-manager="transactionManager"/>

并且在处理业务逻辑的类上采用注解

@Service
public class CustomerServiceImpl implements CustomerService {
@Transactional
public void saveCustomer(Customer customer) {
customerDaoImpl.saveCustomer(customer);
}
...
}
另外在 hibernate 的配置文件中,也可以增加这样的配置来避免这个错误:

<property name="current_session_context_class">thread</property>

spring 中配置sessionFactory及用法的更多相关文章

  1. spring配置文件中配置sessionFactory失败

    配置失败主要原因有两个: <bean id="studentDaoImp" class="com.gxwuz.maven.dao.StudentDaoImp&quo ...

  2. 在Spring中配置SQL server 2000

    前言 Lz主要目的是在Spring中配置SQL server 2000数据库,但实现目的的过程中参差着许多SQL server 2000的知识,也包罗在本文记载下来!(Lz为什么要去搞sql serv ...

  3. Spring中JdbcTemplate的基础用法

    Spring中JdbcTemplate的基础用法 1.在DAO中使用JdbcTemplate 一般都是在DAO类中使用JdbcTimplate,在XML配置文件中配置好后,可以在DAO中注入即可. 在 ...

  4. spring中配置监听队列的MQ

    一.spring中配置监听队列的MQ相关信息注:${}是读取propertites文件的常量,这里忽略.绿色部分配置在接收和发送端都要配置.  <bean id="axx" ...

  5. spring中配置数据源

    spring中配置数据源的几种常见方式: #mysql 数据库配置(jdbc.properties) jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.u ...

  6. 在Spring中配置jdbc为什么不能用${username}问题

    楼主在spring中配置jdbc时,引用的是dbcp.jar包,在dataSource.properties配置文件中,有mysql用户名,楼主自然的选择了使用username,密码是root, 然后 ...

  7. 全面解析Spring中@ModelAttribute注解的用法

    本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:全面解析Spring中@ModelAttribute注解的用法: @ModelAttribute注解用于将方法的参数或方法的返回值绑定到 ...

  8. Spring中配置Hibernate事务管理

    <!-- transationManager --> <bean id="transactionManager" class="org.springfr ...

  9. Spring中配置DataSource数据源的几种选择

    从JNDI获得DataSource. 从第三方的连接池获得DataSource. 使用DriverManagerDataSource获得DataSource. 一.从JNDI获得DataSource ...

随机推荐

  1. SQL Server 索引中include

    SQL Server 索引中include的魅力(具有包含性列的索引) http://www.cnblogs.com/gaizai/archive/2010/01/11/1644358.html 开文 ...

  2. AtCoder Petrozavodsk Contest 001 B - Two Arrays

    Time limit : 2sec / Memory limit : 256MB Score : 300 points Problem Statement You are given two inte ...

  3. MA82G5D16AS16 主频调试记录

    MA82G5D16AS16 主频调试记录 当 SCKS 设置 为 MCKDO / 128 时 MCU 的电流为 0.58mA,100UF 电容可以维持 0.5S,大概可以满足. 但是需要注意外围的线路 ...

  4. SpringCloud微服务实战——第一章序言读书笔记

    什么是微服务架构 是系统架构上的一种设计风格,将独立的系统拆分成多个小型服务,这些小型服务都在各自独立的进程中运行,服务之间基于HTTP的RESTful API进行通信协作. 每个小型服务都围绕各自的 ...

  5. linux swap交换分区说明/管理

    https://coolnull.com/3699.html 一.SWAP说明1.1 SWAP概述当系统的物理内存不够用的时候,就需要将物理内存中的一部分空间释放出来,以供当前运行的程序使用.那些被释 ...

  6. Azure SLB + httpd + ILB + HAProxy + Atlas + MySQL

    为了测试一个环境,需要在Azure上搭建高可用的LAMP架构.但要求MySQL的中间件Atlas采用主备的模式.在数据中心一般采用Keepalive+VIP的模式,通过浮动地址对外提供服务. 但在云环 ...

  7. SpringMVC的环境搭建

    MyBatis框架-->持久层框架-->Object[对象]Relation[关系型数据库]Mapping[在MyBatis的体现是哪个映射文件中国的<resultMap>标签 ...

  8. myeclipse实用快捷键

    笔者这里总结的是个人在使用myeclipse时常用的快捷操作,总结如下: 1.Ctrl +  /             :为选中的一段代码加上或去掉注释符 Ctrl + Shift + /   :( ...

  9. 浅谈Android四大组建之一Service---Service的创建

    Service是安卓四大组件之一,个人觉得Service的使用还是比较简单的额,可以理解为看不见的Activity,因为Service的使用和Activity十分接近.启动啊,生命周期等,都十分简单. ...

  10. Linux split命令实例

    曾经是否想要把一个大文件分割成多个小文件?比如一个5gb日志文件,我们需要把它分成多个小文件,这样我们才有可能使用普通的文本编辑器读取它.有时我们需要传输20gb的大文件到另一台服务器,这就需要我们把 ...