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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • Excel宏编程,给出2列进行去重合并

    Excel宏编程,给出2列进行去重合并Sub去重合并()arr=Worksheets(“sheet1”).Range(“D1”).Clear’选择D列作为存储列,保存最后去重合并的值arr=Worksheets(“sheet1”).UsedRangeDimARowAsLong’A列的行数DimBRowAsLong’B列的行数ARow=Sheet1.Range(“A”&Rows.Count).End(xlUp).Row’不带空格的行数BRow=Sheet1.Range..

    2022年5月25日
  • GOF23—工厂设计模式练习代码和随笔

    GOF23—工厂设计模式练习代码和随笔

    2021年7月13日
  • ubuntu安装增强功能失败_ubuntu参考的对象不支持

    ubuntu安装增强功能失败_ubuntu参考的对象不支持Ubuntu换源后,更新提示GPGerror缺少公钥W:GPGerror:http://mirrors.aliyun.comtrusty-securityInRelease:Thefollowingsignaturescouldn’tbeverifiedbecausethepublickeyisnotavailable:NO_PUBKEY40976EAF437D05B5NO_PUBKEY3B4FE6ACC0B21F32W:GPGerror:http:/

    2022年8月31日
  • Hibernate二级缓存以及ehcache的搭建配置「建议收藏」

    Hibernate二级缓存以及ehcache的搭建配置「建议收藏」Session级别的以及缓存总是有效的,当应用保持持久化实体、修改持久化实体时,Session并不会吧这种改变flush到数据库,而是缓存在当前Session的一级缓存中,除非程序显示调用session的flush方法,或者查询关闭session时,才会把这先改变一次性的flush到底层数据库,这样可以减少与数据库的交互,从而提高数据库的访问性能。SessionFactory级别的二级缓存是全局的,应用的所有的Seeion都共享这个二级缓存,当Session需要抓取数据时,Session就会优

    2022年5月10日
  • DDR,DDR2,DDR3,DDR4,LPDDR区别

    DDR,DDR2,DDR3,DDR4,LPDDR区别DDR,DDR2,DDR3,DDR4,LPDDR区别作者:AirCity2019.12.17Aircity007@sina.com本文所有权归作者Aircity所有1 什么是DDRDDR是DoubleDataRate的缩写,即“双比特翻转”。DDR是一种技术,中国大陆工程师习惯用DDR称呼用了DDR技术的SDRAM,而在中国台湾以及欧美,工程师习惯用DRAM来称呼。DDR的核心…

    2022年10月29日
  • 最新最全Golang面试题(精通篇)

    最新最全Golang面试题(精通篇)Golang面试问题汇总通常我们去面试肯定会有些不错的Golang的面试题目的,所以总结下,让其他Golang开发者也可以查看到,同时也用来检测自己的能力和提醒自己的不足之处,欢迎大家补充和提交新的面试题目.1.Golang中除了加Mutex锁以外还有哪些方式安全读写共享变量Golang中Goroutine可以通过Channel进行安全读写共享变量,还可以通过原子性操作进行.2.无缓冲Chan的发送和接收是否同步ch:=make(chanint)无缓冲的channel由于没有缓

    2022年6月25日

发表回复

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

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