用Java+xml配置方式實現Spring資料事務(程式設計式事務)
阿新 • • 發佈:2018-12-19
一、用Java配置的方式
1、實體類:
Role
public class Role { private int id; private String roleName; private String note; @Override public String toString() { return "Role{" + "id=" + id + ", roleName='" + roleName + '\'' + ", note='" + note + '\'' + '}'; }View Codepublic Role() { } public Role(int id, String roleName, String note) { this.id = id; this.roleName = roleName; this.note = note; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoleName() {return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
2、介面
RoleService
3、實現類
RoleServiceImpl
package com.wbg.springtransaction.service; import com.wbg.springtransaction.config.JavaConfig; import com.wbg.springtransaction.entity.Role; import org.apache.ibatis.session.SqlSessionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import javax.sql.DataSource; import javax.transaction.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @Service public class RoleServiceImpl implements RoleService { @Autowired DataSource dataSource; @Autowired private PlatformTransactionManager transactionManager = null; @Override public List<Role> listAll() { List<Role> list = new ArrayList<Role>(); Connection connection = null; try { connection = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } String sql = "select * from role"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); Role role = null; while (resultSet.next()) { role = new Role( resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3) ); list.add(role); } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } public int insert(Role role) { Connection connection = null; DefaultTransactionDefinition dtd = new DefaultTransactionDefinition(); dtd.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus ts = transactionManager.getTransaction(dtd); String sql = "insert into role(role_name,note) values(?,?)"; PreparedStatement preparedStatement = null; try { connection = dataSource.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, role.getRoleName()); preparedStatement.setString(2, role.getNote()); preparedStatement.executeUpdate(); transactionManager.commit(ts); } catch (SQLException e) { transactionManager.rollback(ts); System.out.println("原因:" + e.getMessage()); } return 0; } }View Code
4、配置:
JavaConfig
@Configuration @ComponentScan("com.wbg.springtransaction.*") @EnableTransactionManagement public class JavaConfig implements TransactionManagementConfigurer { @Bean(name = "dataSource") public DataSource getDataSource() { ComboPooledDataSource dataSource=new ComboPooledDataSource(); try { dataSource.setDriverClass("org.mariadb.jdbc.Driver"); } catch (PropertyVetoException e) { e.printStackTrace(); } dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics"); dataSource.setUser("root"); dataSource.setPassword("123456"); dataSource.setMaxPoolSize(30); return dataSource; } @Override @Bean("transactionManager") public PlatformTransactionManager annotationDrivenTransactionManager() { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); transactionManager.setDataSource(getDataSource()); return transactionManager; } }View Code
5、測試:
public static void main(String[] args) throws SQLException { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class); RoleService roleService = applicationContext.getBean(RoleService.class); roleService.insert(new Role(1,"asd","ss")); for (Role role : roleService.listAll()) { System.out.println(role); } }View Code
二、用xml進行配置:
1、建立xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!--配置資料來源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="org.mariadb.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/wbg_logistics" /> <property name="user" value="root" /> <property name="password" value="123456" /> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <property name="autoCommitOnClose" value="false" /> <property name="checkoutTimeout" value="10000" /> <property name="acquireRetryAttempts" value="2" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> </beans>View Code
2、配置:
@Configuration @ComponentScan("com.wbg.springtransaction.*") @EnableTransactionManagement @ImportResource({"classpath:spring-cfg.xml"}) public class JavaConfig implements TransactionManagementConfigurer { }
3、實現類RoleServiceImpl不變
4、測試:
public static void main(String[] args) throws SQLException { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class); RoleService roleService = applicationContext.getBean(RoleService.class); roleService.insert(new Role(1,"asd","ss")); for (Role role : roleService.listAll()) { System.out.println(role); } }