Spring4 与 Hibernate4 整合过程中的问题记录

Spring4使用注解配置,很方便也很有趣,就是有一些坑需要自己去发现和解决,笔者列出自己在使用过程中遇到的问题,希望对您有所帮助。

1、如果使用hibernate.cfg.xml配置文件配置Hibernate4,必须要在Spring配置文件中(例如applicationContext.xml)配置dataSource,否则编译器会报错。

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
          p:driverClass="com.mysql.jdbc.Driver"
          p:jdbcUrl="jdbc:mysql://localhost:3306/bunny"
          p:user="root"
          p:password="123"
    />
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocations">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="dataSource" ref="dataSource"/>
    </bean>

2、错误:org.hibernate.HibernateException: save is not valid without active transaction

解决方法:hibernate.cfg.xml 不能 有以下字段:

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

3、错误: org.hibernate.HibernateException: No Session found for current thread

解决方法:在Spring配置文件中增加注解配置的事务驱动:

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

4、错误:java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

解决方法:导入aopalliance.jar,注意该文件不能和aopalliance-alpha1.jar同时存在,否则API会冲突。

原文地址:https://www.cnblogs.com/gugia/p/4626196.html