spring事务配置

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mush_me/article/details/84901823
[quote]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="no">

<bean id="personService" class="info.frady.service.person.impl.PersonServiceImpl">
<property name="personDAO">
<ref bean="personDAO"/>
</property>
</bean>
<bean id="personDAO" class="info.frady.dao.person.impl.PersonDAOImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<!-- 开始事务的配置 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="query*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="get*">PROPAGATION_REQUIRED</prop>
<prop key="find*">PROPAGATION_REQUIRED</prop>
<prop key="load*">PROPAGATION_REQUIRED</prop>
<prop key="change*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>

</property>
</bean>

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" lazy-init="false">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
</list>
</property>
</bean>
<!-- SessionFactory将hibernate的配置文件hibernate.cfg.xml的 内容可以通过这块来转移 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="mappingDirectoryLocations">
<list><value>classpath:info/frady/pojo</value><!-- 子目录可以自动遍历 -->
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>info/frady/pojo/person/Person.hbm.xml</value>可以添加多行
</list>
</property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop><!-- 是否打印sql -->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop><!-- 是否格式化打印的sql -->
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.connection.release_mode">${hibernate.connection.release_mode}</prop>
<prop key="hiberante.autoReconnect">${hibernate.autoReconnect}</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
</props>
</property>
</bean>
<!-- dataSource config -->
<bean id ="dataSource" class ="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>${dataSource.driverClassName}</value></property>
<property name="url"><value>${dataSource.url}</value></property>
<property name="username"><value>${dataSource.username}</value></property>
<property name="password"><value>${dataSource.password}</value></property>
</bean>
</beans>
[/quote]


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">

<!-- 对dataSource 数据源进行事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>

<!-- 事务管理 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 对insert,update,delete 开头的方法进行事务管理,只要有异常就回滚 -->
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<!-- <tx:method name="generate*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> -->

<!-- select,count开头的方法,开启只读,提高数据库访问性能 -->
<tx:method name="select*" read-only="true"/>
<tx:method name="count*" read-only="true"/>

<!-- 对其他方法 使用默认的事务管理 -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

<!-- 事务 aop 配置 -->
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* cn.sjj.web.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>

<!-- 配置使Spring采用CGLIB代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>

<!-- 启用对事务注解的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>


cn.sjj.web.service.mclient.impl.HotelServiceImpl implements HotelService
展开阅读全文

spring多数据源事务配置

09-13

我们项目现在需要做一个数据同步的功能,使用两个数据源链接两个不同地址相同结构的数据库(MySQL),我配置了AbstractRoutingDataSource来切换数据源。rn使用定时器每小时调用A数据库数据保存到B中。其中需要配置事务,如果A出错AB都要回滚。这一步不知道是不是需要使用分布式事务(Atomikos)?rnrncontext.xml:rn[code=html]rnrn rn rn rn rn $jdbc.local.urlrn $jdbc.local.usernamern $jdbc.local.passwordrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn $jdbc.remote.urlrn $jdbc.remote.usernamern $jdbc.remote.passwordrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrn rn rn rn rn rn $hibernate.dialectrn $hibernate.show_sqlrn $hibernate.format_sqlrn rn rn rn rn com.ht.ourally.*.entityrn com.ht.mobile.*.entityrn com.ht.alipay.entityrn rn rn rnrn rn rn truern rn rnrn rn rn rnrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrnrn rnrnrn rn rn rn[/code]rnrnDynamicDataSource:rn[code=java]rnpublic class DynamicDataSource extends AbstractRoutingDataSource rnrn @Overridern protected Object determineCurrentLookupKey() rn return DBContextHolder.getCustomerType();rn rnrn[/code]rnDBContextHolder:rn[code=java]rnpublic class DBContextHolder rnrn public static final String DATASOURCE_LOCAL = "dataSourceLocal";rnrn public static final String DATASOURCE_REMOTE = "dataSourceRemote";rnrn private static final ThreadLocal contextHolder = new ThreadLocal();rnrn public static void setCustomerType(String customerType) rn contextHolder.set(customerType);rn rnrn public static String getCustomerType() rn return contextHolder.get();rn rnrn public static void clearCustomerType() rn contextHolder.remove();rn rnrnrn[/code]rnTakeRemoteTask定时器:rn[code=java]rn@Scheduled(cron = "*/5 * * * * ?")rn public void main() rn System.out.println("==========================抓取远程数据库数据开始");rn try rn this.doBaseCompany();rn System.out.println("==========================抓取远程数据库数据结束");rn catch (Exception e) rn e.printStackTrace();rn rn rnrn /**rn * @Title: doBaseCompanyrn * @Description: TODO 物业企业任务rn * @author lindapengrn * @returnrn */rn private boolean doBaseCompany() rn if (!Boolean.valueOf(prop.get("BaseCompany").toString()))rn return true;rn System.err.println(DBContextHolder.getCustomerType());rn DBContextHolder.setCustomerType(DBContextHolder.DATASOURCE_LOCAL); // 切换数据源到本地rn System.err.println(DBContextHolder.getCustomerType());rn SysRole role = new SysRole();rn role.setCompanyId("lindp1");rn role.setRoleName("lindp1");rn sysRoleService.addSysRole(role);rnrn System.err.println(DBContextHolder.getCustomerType());rn DBContextHolder.setCustomerType(DBContextHolder.DATASOURCE_REMOTE); // 切换数据源到远程rn System.err.println(DBContextHolder.getCustomerType());rn SysRole role2 = new SysRole();rn role2.setCompanyId("lindp2");rn role2.setRoleName("lindp2");rn sysRoleService.addSysRole(role2);rn return true;rn rn[/code]rnrn我以这种配置运行有两种问题:rn1.切换数据源无效,lindp1和lindp2都会保存到远程数据库中rn2.去除事务配置后切换数据源正常,只是没有事务了 论坛

Spring 事务配置异常

09-25

各位好,小弟初学Spring想通过AOP配置将Hibernate数据库事务扩展到DAO层,防止出现懒加载异常。可是通过配置发现在进行单元测试时系统一直报错,所以特来请教请各位帮忙看看是什么问题,谢谢了!rnrn以下为Spring 事务配置文件:rn[code=XML]rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn[/code] rnrn其中的DAO层我有使用了泛型结构大致如下:rnAreaDaoImpl.java rn[code=Java]rn public class AreaDaoImpl extends HibernateDaoImpl implements rn IAreaDao rn ............ rn rn[/code] rnrnHibernateDaoImpl.java rn[code=Java]rnpublic class HibernateDaoImpl extends rn HibernateDaoSupport rn public Class queryClass;rnrn @SuppressWarnings("unchecked")rn public HibernateDaoImpl() rn Type genType = getClass().getGenericSuperclass();rn Type[] parames = ((ParameterizedType) genType).getActualTypeArguments();//这一行有错rn queryClass = (Class) parames[0];rn rn ......rnrn rn[/code]rnrn系统报的错误是:rn[code=Assembly]rnorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'areaDao' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class mycompany.servicesystem.dao.impl.AreaDaoImpl]: Common causes of this problem include using a final class or a non-visible class; nested exception is net.sf.cglib.core.CodeGenerationException: java.lang.ClassCastException-->java.lang.Class cannot be cast to java.lang.reflect.ParameterizedTypernat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)rnat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)rnat java.security.AccessController.doPrivileged(Native Method)rnat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)rnat org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)rnat org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)rnat org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)rnat org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)rnat org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)rnat org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)rnat org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)rnat org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)rnat org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)rnat org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)rnat mycompany.servicesystem.common.ContextUtil.getApplicationContext(ContextUtil.java:11)rnat mycompany.servicesystem.dao.TestDepartmentDao.setUp(TestDepartmentDao.java:39)rnBeforeAndAfterRunner.java:74)rnat org.junit.internal.runners.BeforeAndAfterRunner.runBefores(BeforeAndAfterRunner.java:50)rnat org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:33)rnat org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)rnat org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)rnat org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66)rnat org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)rnat org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)rnat org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)rnat org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)rnat org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)rnat org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rnat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)rn... 35 morernCaused by: net.sf.cglib.core.CodeGenerationException: java.lang.ClassCastException-->java.lang.Class cannot be cast to java.lang.reflect.ParameterizedTypernat net.sf.cglib.core.ReflectUtils.newInstance(ReflectUtils.java:235)rnat net.sf.cglib.core.ReflectUtils.newInstance(ReflectUtils.java:220)rn... 41 morernCaused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedTypernat mycompany.servicesystem.dao.base.impl.HibernateDaoImpl.(HibernateDaoImpl.java:50)rnat mycompany.servicesystem.dao.impl.AreaDaoImpl.(AreaDaoImpl.java:26)rnat mycompany.servicesystem.dao.impl.AreaDaoImpl$$EnhancerByCGLIB$$f9ab0600.()rn... 49 more rnrn[/code]rnrn网上我也查了一下资料,把下文中的proxy-target-class="true"去掉。 rn[code=XML]rn rn rn rnrn[/code]rnrn程序虽然不在启动时抛异常,而在进行查询时抛的异常,这个异常我看了一下是与懒加载有关的,我查了一下我的代码,我的确进行了延迟加载。rnrn但我又有一个疑问,我不是给所有的DAO加了事务处理了吗,那也就意味着在事务中会打开Session应该不存在懒加载的问题。rnrn但这里却有这个问题请大家帮帮我!!!!rnrn下文是去除proxy-target-class="true"后系统给的异常信息 rnrn[code=Assembly]rn(hibernate.LazyInitializationException 19 ) failed to lazily initialize a collection of role: mycompany.servicesystem.entities.Area.Departments, no session or session was closedrnorg.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mycompany.servicesystem.entities.Area.Departments, no session or session was closedrnat org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)rnat org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)rnat org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)rnat org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)rnat org.hibernate.collection.PersistentSet.toArray(PersistentSet.java:146)rnat java.util.ArrayList.(ArrayList.java:131)rnat mycompany.servicesystem.dao.impl.AreaDaoImpl.getDepartmentById(AreaDaoImpl.java:84)rnat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rnat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rnat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rnat java.lang.reflect.Method.invoke(Method.java:597)rnat org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:304)rnat org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)rnat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)rnat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)rnat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)rnat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)rnat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)rnat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)rnat $Proxy7.getDepartmentById(Unknown Source)rnat mycompany.servicesystem.dao.TestAreaDao.testGetDepartmentById(TestAreaDao.java:65)rnat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rnat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rnat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rnat java.lang.reflect.Method.invoke(Method.java:597)rnrn[/code]rnrn附:有的大虾可能会说我为什么把事务放在DAO层,那是因为我现在正进行DAO层代码编写后继我会放在Service层去的,所以请大虾回答问题时不要指出这点问题! rnrn 论坛

没有更多推荐了,返回首页