您的位置:首页 > 编程语言 > Java开发

springMVC整合hibernate的时候数据插入需要flush问题

2015-04-11 18:03 423 查看

hibernate中openSession和getCurrentSession

openSession需要手动的管理事务,每次打开一个新的session

getCurrentSession在当前线程中找一个session,如果没有则新建一个。不需要手动close,但是需要定义事务管理

spring配合hibernate使用getCurrentSession

由于使用getCurrentSession需要使用事务,spring和hibernate整合的时候使用spring接管hibernate的事务

步骤如下:

1.需要在spring的web.xml中配置session open

web.xml加入配置

<!-- 配置Session -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


2.凡是加上事务的bean,必须用xml的方式配置,不能用注解

(事务可以使用注解,测试环境 spring3.2.10+hibernate4.1.9)

例如:SecurityService类中有配置事务

application.xml

<bean id="securityService" class="nanhu.lf.service.SecurityService" />


SecurityService类

package nanhu.lf.service;
import java.util.List;
import nanhu.lf.dao.UserDAO;
import nanhu.lf.model.TestObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
public class SecurityService {

@Autowired
private UserDAO userDAO;

@Transactional
public void saveUser(TestObj user){
userDAO.saveUser(user);
}

@Transactional
public List<TestObj> getAllUser(){
return userDAO.findAll();
}
}


3.配置事务 (注解和xml方式都可以)

1.使用注解方式:

<!-- 配置注解管理事务-->
<tx:annotation-driven transaction-manager="txManager"/>


2.使用xml方式

<!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager   -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" read-only="false"/>
<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>
<aop:pointcut id="serviceMethods" expression="execution(* nanhu.lf.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config>


事务管理器如下:

<!-- 事物管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>


这个也许是使用springMVC之后导致的一个bug吧,或者还有什么其他的配置,网上很多说法,感觉最靠谱的还是 spring容器和springMVC容器之间存在父子关系,那么装配带有事务的bean的时候可能出现重复,所以才会加载的是没有事务的service,具体还不清楚。

在spring的配置文件中,和MVC相关的bean配置在spring-servlet.xml中,其他的放在是spring.xml(application.xml)中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息