1、SpringMVC事务配置SpringMVC事务配置本文介绍两种配置方法:一、XML,使用tx标签配置拦截器实现事务一、Annotation方式以下所使用环境为Spring4.0.3、Hibernate4.3.5一、XML,使用tx标签配置拦截器实现事务Entity类User.java,持久化类,对应数据库表userpackagecom.lei.demo.entity;importjavax.persistence.*;Entity(name=users)publicclassUserspublicUsers()super();IdGeneratedValue(strategy=Generat
2、ionType.AUTO)Column(name=id)privateIntegerid;Column(name=user_name,length=32)privateStringuser_name;Column(name=age)privateIntegerage;Column(name=nice_name,length=32)privateStringnice_name;/属性实现.UserDAO.javar,表user的一些操作,其中属性sessionFactory应该由Spring注入,如下:packagecom.lei.demo.dao;importjava.util.List;im
3、portjavax.annotation.Resource;importorg.hibernate.Query;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.springframework.stereotype.Repository;importcom.lei.demo.entity.Users;publicclassUsersDAOprivateSessionFactorysessionFactory;publicvoidsetSessionFactory(SessionFactorysess
4、ionFactory)this.sessionFactory=sessionFactory;publicSessionFactorygetSessionFactory()returnsessionFactory;publicListgetAllUser()Stringhsql=fromusers;Sessionsession=sessionFactory.getCurrentSession();Queryquery=session.createQuery(hsql);returnquery.list();UserService.java,业务实现类,如下packagecom.lei.demo.
5、service;importjavax.annotation.Resource;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Isolation;importorg.springframework.transaction.annotation.Propagation;importorg.springframework.transaction.annotation.Transactional;importcom.lei.demo.dao.*;publicc
6、lassUserServiceprivateUsersDAOuserDao;publicintuserCount()returnuserDao.getAllUser().size();publicUsersDAOgetUserDao()returnuserDao;publicvoidsetUserDao(UsersDAOuserDao)this.userDao=userDao;首先看一下xml配置,spring-hibernate.xml如下:com.lei.demo.entity$hibernate.hbm2ddl.auto$hibernate.dialect$hibernate.show_
7、sql!-thread-其中主要配置中是tx:advice和aop:config两个配置节,以SpringAOP的方式实现事务管理。tx:advice配置了事务的管理者是transactionManager,同时tx:method也规定了如果方法名匹配“add*”和“get*”方法时使用事务,propagation是设定事务的传播级别。除了“add*”和“get*”方法,其他的方法的事务是只读的(典型地,对于只执行查询的事务你会将该属性设为true,如果出现了更新、插入或是删除语句时只读事务就会失败)aop:config指定了一个aop:pointcut去引用上边的advice。这样就通过AO
8、P的拦截机制实现了事务,当然你还要用Spring的方式自己配置UserDAO和UserService。二、Annotation方式第一步,首先看一下web.xml,如下:ArchetypeCreatedWebApplicationcontextConfigLocationclasspath:/spring-*.xmlorg.springframework.web.context.ContextLoaderListenerlei-dispatcherorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclas
9、spath:/lei-dispatcher-servlet.xml1lei-dispatcher/第二步,spring-hibernate配置,见以下spring-hibernate.xml配置com.lei.demo.entity$hibernate.hbm2ddl.auto$hibernate.dialect$hibernate.show_sql!-thread-第一节中xml配置事务中需要通过配置tx:advice和aop:config来增加事务的功能。此处采用全注释方法,这两个配置节就不需要了。相应的需要在视图解析配置中启用注释,如下lei-dispatcher-servlet.xml/WEB-
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1