spring 中配置sessionFactory及用法

spring 中配置sessionFactory及用法spring中配置sessionFactory及用法方法一:1、在Spring的applicationContext.xml中配置bean<!–启用注解注入–><c

大家好,又见面了,我是你们的朋友全栈君。

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>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/155203.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • mysql—mysql中如何存储日期数据

    mysql—mysql中如何存储日期数据

    2020年11月12日
    188
  • Landsat 8 地表反射率数据介绍—— Landsat 8 Surface Reflectance Tier 1

    Landsat 8 地表反射率数据介绍—— Landsat 8 Surface Reflectance Tier 1USGSLandsat8SurfaceReflectanceTier1该数据集是来自Landsat8OLI/TIRS传感器的经大气校正的表面反射率。图像包含4个可见光和一个近红外(VNIR)波段和2个短波红外(SWIR)波段两个热红外。经过正射校正后的表面反射率,以及2个热红外经过正交校正后的亮度温度这些数据已使用LaSRC进行了大气校正,包括使用CFMASK生成的云,阴影…

    2022年7月23日
    37
  • activex控件无法安装解决方法

    activex控件无法安装解决方法2015-01-06有人的电脑ie上了11的版本。结果怎么也安装不了一些activex的控件。总是被阻止。改了安全也不会好用的。因为微软IE博客介绍:“由于日益严峻的恶意网络、不断增长的恶意网页数量,因此用户非常需要确保IE浏览器ActiveX控件及时升级至最新版,从而免受各类安全漏洞攻击。”本项“Out-Of-DateActiveX(过时ActiveX控件)”拦截功能,适用于Win7SP…

    2022年5月15日
    51
  • Java学习之Spring Boot入门

    Java学习之SpringBoot入门0x00前言学习完ssm的整合后,开始来学习SpringBoot,在前面学习Spring的时候会发现使用Spring开发中配置Spring的环境会非常的

    2021年12月12日
    56
  • STM32的IWDG(独立看门狗)详细用法

    STM32的IWDG(独立看门狗)详细用法文章出处:https://www.cnblogs.com/Liu-Jing/p/7243029.html章参考资料:《STM32F4XX中文参考手册》IWDG章节。1、IWDG简介:  STM32有两个看门狗,一个是独立看门狗另外一个是窗口看门狗,独立看门狗号称宠物狗,窗口看门狗号称警犬,本章我们主要分析独立看门狗的功能框图和它的应用。独立看门狗用通俗一点的话来解释就是一个12位的递减计…

    2022年6月14日
    54
  • 双向链表排序[通俗易懂]

    双向链表排序[通俗易懂]双向链表的结构体,包括一个前驱节点的指针、一个后继节点的指针以及一个存储数据的data域,initList函数初始化单节点的双链表,addList函数采用头插入方法添加一个节点到双链表中,sort函数实现了对双链表的排序,采用头插入方式建成的双链表的头结点(存储65535的那个节点)必然在末尾(其实双链表没有首尾之说,只是把它当作末尾),排序的时候,1.首先从该节点处,每次查找前驱节点,并记录da…

    2022年10月11日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号