spring事务管理

42 阅读1分钟

<beans xmlns="www.springframework.org/schema/bean…"

xmlns:xsi="www.w3.org/2001/XMLSch…"

xmlns:context="www.springframework.org/schema/cont…"

xmlns:aop="www.springframework.org/schema/aop"

xmlns:tx="www.springframework.org/schema/tx"

xsi:schemaLocation="www.springframework.org/schema/bean…

www.springframework.org/schema/bean…

www.springframework.org/schema/cont…

www.springframework.org/schema/cont…

www.springframework.org/schema/aop

www.springframework.org/schema/aop/…

www.springframework.org/schema/tx

www.springframework.org/schema/tx/s…

<property name="url"

value="jdbc:mysql://localhost:3306/hjx_jdbc?serverTimezone=GMT" />

<bean id="jdbcTemplate"

class="org.springframework.jdbc.core.JdbcTemplate">

<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">

tx:attributes

<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"

read-only="false" />

</tx:attributes>

</tx:advice>

aop:config

<aop:pointcut expression="execution(* com.jdbc..(..))"

id="txPointCut" />

<aop:advisor pointcut-ref="txPointCut" advice-ref="txAdvice" />

</aop:config>

<context:annotation-config />

<context:component-scan base-package="com.jdbc" />

删除事务

// 事务管理 对数据进行删除

public int tranferUser_Del(int id) {

String sql="delete from user where id=?";

Object[] obj=new Object[]{

id

};

int count=this.jdbcTemplate.update(sql,obj);

// 如果事务管理成功,因为下一行出错则数据不会删除成功

int i=1/0;

return count;

}

单元测试

@Test

public void transfer(){

int count=user.tranferUser_Del(3);

if(count>=0){

System.out.println("事务处理成功!");

}

else{

System.out.println("事务处理失败");

}