JDBC的事务管理在Spring2.0下有两种编程式的实现
PlatformTransactionManager
TransactionTemplate
对于PlatformTransctionManager,通常,不直接使用它,而是使用它的实现类DataSourceTransactionManager。
import com.gctx.framework.dao.IGenericJdbcDAO;
import com.gctx.framework.logs.Logit;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public boolean tran(List<String> sqls)
{
if ((null == sqls) || (sqls.size() <= 0)) {
return false;
}
PlatformTransactionManager ptm = new DataSourceTransactionManager(getDataSource());
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = ptm.getTransaction(def);
try {
for (int i = 0; i < sqls.size(); i++) {
getJdbcTemplate().execute((String)sqls.get(i));
}
ptm.commit(status);
return true;
} catch (Exception e) {
ptm.rollback(status);
}
return false;
}
PlatformTransactionManager
TransactionTemplate
对于PlatformTransctionManager,通常,不直接使用它,而是使用它的实现类DataSourceTransactionManager。
import com.gctx.framework.dao.IGenericJdbcDAO;
import com.gctx.framework.logs.Logit;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public boolean tran(List<String> sqls)
{
if ((null == sqls) || (sqls.size() <= 0)) {
return false;
}
PlatformTransactionManager ptm = new DataSourceTransactionManager(getDataSource());
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = ptm.getTransaction(def);
try {
for (int i = 0; i < sqls.size(); i++) {
getJdbcTemplate().execute((String)sqls.get(i));
}
ptm.commit(status);
return true;
} catch (Exception e) {
ptm.rollback(status);
}
return false;
}