在使用spring3和hibernate4.2集成与hibernate3有很多的不同,其中之一就是spring3不在支持HibernateTemplate,而是使用hibernate原生的api,我在集成的时候遇到了如下两个问题。
[color=red]问题之一:在使用session.save()方法保存数据时不能成功的保存到数据库[/color]
这个问题的原因是在获取session时,不能使用openSession()方法,而要使用getCurrentSession()方法
[color=red]问题之二:使用getCurrentSession时报:hibernate4 org.hibernate.HibernateException: No Session的错误[/color]
这个问题的原因是session未打开,解决方式:
前提记得在service层上面加上@Transaction注释,否则任然会有相同的异常
方式1-在web.xml中加过滤器
方式2-配置事务的切面
[color=red]问题之一:在使用session.save()方法保存数据时不能成功的保存到数据库[/color]
这个问题的原因是在获取session时,不能使用openSession()方法,而要使用getCurrentSession()方法
@Resource(name="sf")
private SessionFactory sessionFactory;
Session session ;
...
session = sessionFactory.getCurrentSession();
[color=red]问题之二:使用getCurrentSession时报:hibernate4 org.hibernate.HibernateException: No Session的错误[/color]
这个问题的原因是session未打开,解决方式:
前提记得在service层上面加上@Transaction注释,否则任然会有相同的异常
方式1-在web.xml中加过滤器
<!-- open session filter -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
方式2-配置事务的切面
<!-- 用spring管理事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sf"/>
</bean>
<!-- 配置使用注解的方式来使用事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置那些类的方法进行事务管理,需要aopalliance-1.0.jar和aspectjweaver.jar,当前com.neusoft.leehom.service包中的子包,
类中所有方法需要,还需要参考tx:advice的设置 -->
<!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 需要引入aop的命名空间 -->
<aop:config>
<!-- 切入点指明了在执行Service的所有方法时产生事务拦截操作 -->
<aop:pointcut id="daoMethods" expression="execution(* com.tl..serviceimpl.*.*(..))" />
<!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" />
</aop:config>