在利用Spring声明的事务和Spring提供的对持久层的Template操作数据库的时候,原则上不要在代码里写事务控制的语句(commit).
1,用JdbcTemplate和JDBC集成的时候:
不管拥有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()获得的时候,提交没有影响.(每一次数据库操作都是独立的)
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()提交.