大致开发流程如下:
①准备数据源信息、数据库驱动jar包、spring-jdbc模块;
②使用Spring的JdbcTemplate来操作数据库;
③在@Configuration注解类上添加@EnableTransactionManagement注解,来开启基于注解的事务管理功能;
④注册事务管理器PlatformTransactionManager;
⑤在需要添加事务的方法上,添加@Transactional注解来声明该方法是事务方法;
@Configuration @ComponentScan("com.spring.annotation.jdbc") @EnableTransactionManagement public class JDBConfig { @Bean public PlatformTransactionManager transactionManager(DataSource dataSource){ return new DataSourceTransactionManager(dataSource); } @Bean public DataSource dataSource() throws Exception{ ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("root"); dataSource.setPassword("MyPass@123"); dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/spring?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false"); dataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); dataSource.setMaxPoolSize(10); dataSource.setInitialPoolSize(20); System.out.println(dataSource); return dataSource; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource){ JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate; } } |
@Service public class OrgService { @Autowired private OrgDao orgDao; @Transactional public int insertOrg(String orgcode, String orgname, String areacode){ return orgDao.insert(orgcode,orgname,areacode); } } |