DBMNG数据库管理与应用

才能是来自独创性。独创性是思维、观察、理解和判断的一种独特的方式。
当前位置:首页 > 经验分享 > Java组件

Spring声明事务的时候如果代码中commit

在利用Spring声明的事务和Spring提供的对持久层的Template操作数据库的时候,原则上不要在代码里写事务控制的语句(commit).
1,用JdbcTemplate和JDBC集成的时候:
  1. public void testInsert(int id, String val) {  
  2.     this.jdbcTemplate.update("insert into A (ID, VAL) values (?, ?)", id, val);  
  3.     try {  
  4.         jdbcTemplate.getDataSource().getConnection().commit();  
  5.         System.out.println("  jdbcTemplate.getDataSource().getConnection().commit()");  
  6.     } catch (SQLException e) {  
  7.         // TODO Auto-generated catch block  
  8.         e.printStackTrace();  
  9.     }  
  10. }  


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()获得的时候,提交没有影响.(每一次数据库操作都是独立的)
  1. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  2. MybatiscustomerMapper mapper = ctx.getBean("mybatiscustomerMapper", MybatiscustomerMapper.class);  
  3. Mybatiscustomer customer = new Mybatiscustomer();  
  4. customer.setId(new BigDecimal(1));  
  5. customer.setName("name3");  
  6. mapper.insert(customer); //##this will succeed  
  7. String nullStr = null;  
  8. nullStr.length();  
  9. customer.setId(new BigDecimal(2));  
  10. mapper.insert(customer);//##this will NOT succeed  
C,当有事务声明管理的时候,SqlSession必须是由org.mybatis.spring.SqlSessionTemplate获得才起作用,并且不能在代码中通过sqlSession.commit()提交.
本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号