Spring声明事务的时候如果代码中有commit会发生什么

在利用Spring声明的事务和Spring提供的对持久层的Template操作数据库的时候,原则上不要在代码里写事务控制的语句(commit).
1,用JdbcTemplate和JDBC集成的时候:

	public void testInsert(int id, String val) {
		this.jdbcTemplate.update("insert into A (ID, VAL) values (?, ?)", id, val);
		try {
			jdbcTemplate.getDataSource().getConnection().commit();
			System.out.println("  jdbcTemplate.getDataSource().getConnection().commit()");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

commit语句对testInsert方法没有影响,在由Spring声明的事务管理时,commit不会影响Spring事务.
不管拥有testInsert方法的类是由Spring管理还是通过new的方式创建,jdbcTemplate.getDataSource().getConnection().commit()都不会影响事务.其原因是当没有事务声明的时候,
得到的connect是自动提交的,在jdbcTemplate.getDataSource().getConnection().commit();之前就已经自动提交了,而在有事务声明的时候,.commit()不起作用.
2,用HibernateTemplate集成Hibernate:
配置hibernate的<property name="current_session_context_class">thread</property>的时候,必须在代码中显示管理事务.
由Spring 管理事务的时候,不能配置<property name="current_session_context_class">thread</property>,代码中不能提交.
3,集成MyBatis:
A,MyBatis不和Spring集成的时候,必须由sqlSession.commit()提交,才真正保存数据.
B,在和Spring集成的时候:如果没有声明事务管理,每一次数据库操作是一个事务.
当SqlSession是由org.mybatis.spring.SqlSessionTemplate获得的时候不能在代码里提交.当SqlSession是由SqlSessionFactory.openSession()获得的时候,提交没有影响.(每一次数据库操作都是独立的)

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
MybatiscustomerMapper mapper = ctx.getBean("mybatiscustomerMapper", MybatiscustomerMapper.class);
Mybatiscustomer customer = new Mybatiscustomer();
customer.setId(new BigDecimal(1));
customer.setName("name3");
mapper.insert(customer); //##this will succeed
String nullStr = null;
nullStr.length();
customer.setId(new BigDecimal(2));
mapper.insert(customer);//##this will NOT succeed
C,当有事务声明管理的时候,SqlSession必须是由org.mybatis.spring.SqlSessionTemplate获得才起作用,并且不能在代码中通过sqlSession.commit()提交.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值