Spring DataSourceTransactionManager 事务管理

【Spring DataSourceTransactionManager 事务管理】1.spring.xml



2.configuration.properties
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://127.0.0.1/spring-test?useEncoding=true&characterEncoding=UTF-8 database.username=root database.password=root hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true


3.ProductService.java
package com.spring.dataSourceTransactionManager; public interface ProductService { public void save(Stringsql); public void batch(String[] sql); }


4.ProductServiceImpl.java
package com.spring.dataSourceTransactionManager; import org.springframework.jdbc.core.JdbcTemplate; public class ProductServiceImpl implements ProductService { private JdbcTemplate jdbcTemplate; @Override public void save(String sql) { jdbcTemplate.execute(sql); } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void batch(String[] sql) { jdbcTemplate.batchUpdate(sql); } }


5.测试类Test
package com.spring.dataSourceTransactionManager; import java.sql.SQLException; import javax.naming.NamingException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class Test { public static void main(String[] args) throws NamingException, SQLException { ApplicationContext app = new FileSystemXmlApplicationContext("src/com/spring/dataSourceTransactionManager/spring.xml"); ProductService p = (ProductService)app.getBean("productService"); String[] sql = {"INSERT INTO t_product VALUES (1,'饼干'); " , "INSERT INTO t_receiver VALUES (1,null); "}; p.batch(sql); } }


6.Sql

DROP TABLE IF EXISTS `t_product`; CREATE TABLE `t_product` ( `product_id` bigint(20) NOT NULL auto_increment, `product_title` varchar(255) NOT NULL default '', PRIMARY KEY(`product_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; /*!40000 ALTER TABLE `t_product` ENABLE KEYS */; UNLOCK TABLES; # # Table structure for table t_receiver #DROP TABLE IF EXISTS `t_receiver`; CREATE TABLE `t_receiver` ( `receiver_id` bigint(20) NOT NULL auto_increment, `receiver_name` varchar(40) NOT NULL default '', PRIMARY KEY(`receiver_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40000 ALTER TABLE `t_receiver` ENABLE KEYS */; UNLOCK TABLES;


    推荐阅读