packagecom.wbg.springtransaction.service;importcom.wbg.springtransaction.config.JavaConfig;importcom.wbg.springtransaction.entity.Role;importorg.apache.ibatis.session.SqlSessionException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jdbc.datasource.DataSourceTransactionManager;importorg.springframework.stereotype.Service;importorg.springframework.transaction.PlatformTransactionManager;importorg.springframework.transaction.TransactionStatus;importorg.springframework.transaction.support.DefaultTransactionDefinition;importjavax.sql.DataSource;import javax.transaction.*;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;
@Servicepublic class RoleServiceImpl implementsRoleService {
@Autowired
DataSource dataSource;
@Autowiredprivate PlatformTransactionManager transactionManager = null;
@Overridepublic ListlistAll() {
List list = new ArrayList();
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= newRole(
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();
}
}
}returnlist;
}public intinsert(Role role) {
Connection connection= null;
DefaultTransactionDefinition dtd= newDefaultTransactionDefinition();
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;
}
}