• 编辑
  • 删除

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及用法(JAVA后端)相关推荐

  1. java 获取spring对象数组_解析Java中如何获取Spring中配置的bean

    解析Java中如何获取Spring中配置的bean Java中如何获取Spring中配置的bean?下面是由百分网小编为大家整理的解析Java中如何获取Spring中配置的bean,喜欢的可以收藏一下 ...

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

    Spring中配置DataSource数据源的几种选择 在Spring框架中有如下3种获得DataSource对象的方法: 从JNDI获得DataSource. 从第三方的连接池获得DataSourc ...

  3. Spring中配置Hibernate事务的四种方式

    2019独角兽企业重金招聘Python工程师标准>>> 为了保证数据的一致性,在编程的时候往往需要引入事务这个概念.事务有4个特性:原子性.一致性.隔离性.持久性. 事务的种类有两种 ...

  4. spring中配置数据源

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

  5. spring中配置quartz定时器

    spring中配置quartz定时器 最近项目中用到定时器,项目用的spring所以想在spring中配置一下定时器,看到网上用quartz的比较多,所以就搜了一下.参考:http://blog.cs ...

  6. Spring Bean配置方式之一:Java配置

    简介: Spring bean 是使用传统的 XML 方法配置的.在这篇文章中,您将学习使用基于纯 Java 的配置而非 XML 来编写 Spring bean 并配置它们.本文将介绍可用来配置 be ...

  7. Spring中配置数据源的4种形式

    转自:https://blog.csdn.net/qqqqqq654/article/details/52462203 不管采用何种持久化技术,都需要定义数据源.Spring中提供了4种不同形式的数据 ...

  8. spring多个视图解析器_在Spring中配置多个View解析器

    spring多个视图解析器 1.简介 在Spring中,提供了View Resolver来使用模型中可用的数据来解析视图,而无需与JSP,Velocity或Thymeleaf等View技术紧密绑定. ...

  9. 在Spring中配置多个View解析器

    1.简介 在Spring中,提供了View Resolver来使用模型中可用的数据来解析视图,而无需与JSP,Velocity或Thymeleaf等View技术紧密绑定. Spring可以根据需要轻松 ...

最新文章

  1. Design Pattern - Interpreter(C#)
  2. c++强大还是python强大-2020,你该学习Python还是C++
  3. LeetCode-剑指 Offer 15. 二进制中1的个数
  4. 【软考-软件设计师】计算机指令系统
  5. boost::diagnostic_information_what的用法程序
  6. 中国网建SMS短信接口调用(java发送短信)
  7. flink网页端提交pr-修改文档报错
  8. php中等3秒再跳转,跳转和重定向
  9. 【转】DICOM简述!!!!
  10. Linux进程全解8——exec 族函数
  11. 电力物联网智慧路灯充电桩传感器技术应用方案
  12. openCVPracticalExercise学习笔记04
  13. 关于ajax跨域的问题
  14. mac trace traceroute 简要使用
  15. python常用方法技巧使用总结
  16. 【HDU 5765】Bonds(进制运算妙用)
  17. 换位思考的反思与总结
  18. TCP/IP协议:最大报文段长度(MSS)是如何确定的
  19. matlab代码建立不允许缺货,允许缺货的经济订货批量模型.doc
  20. 微信支付常见错误和统一下单错误码详情

热门文章

  1. FlowPaper js分析:10页限制 及 LOGO设置
  2. SSM三大框架从0到1,无障碍学习,萌新可入《一》
  3. pycharm注释快捷键Ctrl+/无效怎么解决?
  4. 张小白带你体验Jetson AGX Orin的Hello AI World
  5. 国海证券:股票仍是最佳投资品种
  6. 从《蜗居》的小贝学C++谈起:(转)
  7. 布匹瑕疵检测数据集EDA分析
  8. 异常“itunes无法连接iphone 因为收到来自此设备的无效响应”的解决办法
  9. unity给头发添加物理_Unity中如何加入液体物理效果
  10. js数组indexof用法-1 0 1代表的意思