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)
上一篇 2022年7月2日 下午4:46
下一篇 2022年7月2日 下午4:46


相关推荐

  • linux 查看IP地址

    linux 查看IP地址参考资料整理一 在 linux 下可以通过两个命令来查看本机的 IP 地址 1 支持包括 Linux 在内的所有 Unix 系统 sbin ifconfig2 对于 Linux 而言 也可以使用 ip 命令查看 提示 没有 ifconfig 命令时可以用此命令查看 ipaddrshow 二 安装 ifconfig 命令 1 ifconfig 命令是设置或显示网络接口的程序 可以显示出我们机器的网卡信息 可是有些时候最小化安装 CentOS 等 Linux 发行版的时候会默认不安装 ifconfig 等命令 这时候你

    2026年3月26日
    2
  • 特斯拉笔试内容_数据库笔试题

    特斯拉笔试内容_数据库笔试题今天笔试一共两道题,1个小时内答出来,第一题如下两张图所示:正确sql为:selectsensor_id,count(distinctevent_type)fromeventsgroupbysensor_idorderbysensor_id效果如下图:第二道题如下两张图:,答案如下sql:selectid,server_name,casewhenconnections>(selectavg(conne…

    2025年6月21日
    3
  • Java测试题及答案(Java干货完整试卷)

    Java测试题及答案(Java干货完整试卷)都是一些非常非常基础Java入门学习的题,是我最近参加各大IT公司笔试后靠记忆记下来的,经过整理献给与我一样参加各大IT校园招聘的同学们,但是IT公司就喜欢考这些基础的东西,所以为了能进大公司就~~~当复习期末考吧。花了不少时间整理,在整理过程中也学到了很多东西,请大家认真对待每一题~~~一、填空题。(每空2分,共计20分)1.boolean类型的可能取值有(true)和(false)。2.在JDK1.6中switch选择结构能判断的数据类型只能是(int)和(char)…

    2022年7月9日
    20
  • (转)java 数组转字符串 字符串转数组

    (转)java 数组转字符串 字符串转数组java 数组转字符串字符串转数组转载地址 https www cnblogs com ooo0 p 9169311 html 字符串转数组使用 Javasplit 方法 split 方法根据匹配给定的正则表达式来拆分字符串 注意 和 等转义字符 必须得加 多个分隔符 可以用 作为连字符 字符串转数组 java la

    2025年10月31日
    6
  • re模块和正则表达式[通俗易懂]

    正则表达式序言在如今这个网络横行的时代,网络对我们的生活起着举足轻重的作用,在我们日常生活中是随处可见的:坐车买票,日常生活物品的购买,医院就医。。。。在我们网上购物的时候会进入登陆界面进行一系列

    2022年3月29日
    40
  • Vim配置文件vimrc入门介绍

    Vim配置文件vimrc入门介绍本文转载自:vim教程网Vim入门级基础配置-Vim入门教程(1)介绍Vim配置文件.vimrc,配置Vim显示行号、支持utf8中文不乱码、突出显示Vim当前行,设置高亮显示括号匹配和tab缩进,解决Vim粘贴时多出缩进和空格问题。一、Vim配置文件.vimrcVim编辑器相关的所有功能开关都可以通过.vimrc文件进行设置。.vimrc配置文件分系统配置和用户配置两种。系…

    2022年4月30日
    111

发表回复

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

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