1、用jdbc操作数据库举例,在导入了aop和spring依赖以外,导入sping-jdbc依赖,先创建配置类TxConfig,在类中注册了三个bean
dataSource
jdbcTemplate
platformTransactionManager
还有@EnableTransactionManagement//开启基于注解的事务管理功能 千万不能忘记!
package crm.mytest.tc; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.beans.PropertyVetoException; @EnableTransactionManagement//开启基于注解的事务管理功能,重要!!! @Configuration @ComponentScan("crm.mytest.tc") public class TxConfig { /** * DataSource * @return * @throws PropertyVetoException */ @Bean public DataSource dataSource() throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("root"); dataSource.setPassword("123"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql:///crm"); return dataSource; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource){ JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate; } //注册事务管理器在容器中,重要!!! @Bean public PlatformTransactionManager platformTransactionManager() throws PropertyVetoException { return new DataSourceTransactionManager(dataSource());//放入数据源 } }
2、简略的创建一个UserDao和UserService,模拟一下开发的mvc模式,这里就先不用接口了
package crm.mytest.tc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void insert(){ String sql="insert into test values(?,?,?)"; jdbcTemplate.update(sql, null, "liweijun",1); } }
package crm.mytest.tc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class UserService { @Autowired private UserDao userDao; @Transactional public void insert(){ userDao.insert(); System.out.println("插入完成"); // int i=1/0; } }
3、最后是测试类
package crm.mytest.tc; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = crm.mytest.tc.TxConfig.class) public class Demo { @Autowired private UserService userService; @Test public void demo1(){ userService.insert(); } }
最后可以自行测试在service层中制造异常,看是否回滚了