一:commons-dbutils简介mysql
commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,而且使用dbutils能极大简化jdbc编码的工做量,同时也不会影响程序的性能。sql
DbUtils提供了三个包,分别是:
org.apache.commons.dbutils;
org.apache.commons.dbutils.handlers;
org.apache.commons.dbutils.wrappers;数据库
(1)org.apache.commons.dbutils
DbUtils 关闭连接等操做
QueryRunner 进行查询的操做apache
(2)org.apache.commons.dbutils.handlers
ArrayHandler :将ResultSet中第一行的数据转化成对象数组
ArrayListHandler将ResultSet中全部的数据转化成List,List中存放的是Object[]
BeanHandler :将ResultSet中第一行的数据转化成类对象
BeanListHandler :将ResultSet中全部的数据转化成List,List中存放的是类对象
ColumnListHandler :将ResultSet中某一列的数据存成List,List中存放的是Object对象
KeyedHandler :将ResultSet中存成映射,key为某一列对应为Map。Map中存放的是数据
MapHandler :将ResultSet中第一行的数据存成Map映射
MapListHandler :将ResultSet中全部的数据存成List。List中存放的是Map
ScalarHandler :将ResultSet中一条记录的其中某一列的数据存成Object数组
(3)org.apache.commons.dbutils.wrappers
SqlNullCheckedResultSet :对ResultSet进行操做,改版里面的值
StringTrimmedResultSet :去除ResultSet中中字段的左右空格。Trim()安全
二:JDBC开发中的事务处理多线程
开发中,对数据库的多个表或者对一个表中的多条数据执行更新操做时要保证对多个更新操做要么同时成功,要么都不成功,这就涉及到对多个更新操做的事务管理问题了。并发
(1)在数据访问层(Dao)中处理事务app
/**
* @Method: transfer
* @Description:
* 在开发中,DAO层的职责应该只涉及到CRUD,
* 因此在开发中DAO层出现这样的业务处理方法是彻底错误的
* @throws SQLException
*/
public void transfer() throws SQLException{
Connection conn = null;
try{
conn = JdbcUtils.getConnection();
//开启事务
conn.setAutoCommit(false);jsp
/**
* 在建立QueryRunner对象时,不传递数据源给它,是为了保证这两条SQL在同一个事务中进行,
* 咱们手动获取数据库链接,而后让这两条SQL使用同一个数据库链接执行
*/
QueryRunner runner = new QueryRunner();
String sql1 = "update account set money=money-100 where name=?";
String sql2 = "update account set money=money+100 where name=?";
Object[] paramArr1 = {param1};
Object[] paramArr2 = {param2};
runner.update(conn,sql1,paramArr1);
//模拟程序出现异常让事务回滚
int x = 1/0;
runner.update(conn,sql2,paramArr2);
//sql正常执行以后就提交事务
conn.commit();
}catch (Exception e) {
e.printStackTrace();
if(conn!=null){
//出现异常以后就回滚事务
conn.rollback();
}
}finally{
//关闭数据库链接
conn.close();
}
}
在开发中,DAO层的职责应该只涉及到基本的CRUD,不涉及具体的业务操做,因此在开发中DAO层出现这样的业务处理方法是一种很差的设计
(2)在业务层(Service)处理事务
先改造DAO:
public class TextDao {
//接收service层传递过来的Connection对象
private Connection conn = null;
public TextDao(Connection conn){
this.conn = conn;
}
public TextDao(){
}
/**
* @Method: update
* @Description:更新
* @Anthor:
* @param user
* @throws SQLException
*/
public void update(Account account) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "update account set name=?,money=? where id=?";
Object params[] = {account.getName(),account.getMoney(),account.getId()};
//使用service层传递过来的Connection对象操做数据库
qr.update(conn,sql, params);
}
/**
* @Method: find
* @Description:查找
* @Anthor:
* @param id
* @return
* @throws SQLException
*/
public Account findById(int id) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "select * from account where id=?";
//使用service层传递过来的Connection对象操做数据库
return (Account) qr.query(conn,sql, id, new BeanHandler(Account.class));
}
}
接着对Service(业务层)中的transfer方法的改造,在业务层(Service)中处理事务
/**
* @ClassName: TextService
* @Description: 业务逻辑处理层
* @author:
* @date:
*
*/
public class TextService {
/**
* @Method: transfer
* @Description:这个方法是用来处理两个用户之间的转帐业务
* @Anthor:
* @param sourceid
* @param tartgetid
* @param money
* @throws SQLException
*/
public boolean transfer(int sourceid,int tartgetid,float money) throws SQLException{
Connection conn = null;
boolean flag = false;
try{
//获取数据库链接
conn = JdbcUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
//将获取到的Connection传递给TextDao,保证dao层使用的是同一个Connection对象操做数据库
TextDao dao = new TextDao(conn);
Account source = dao.find(sourceid);
Account target = dao.find(tartgetid);
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
dao.update(source);
//模拟程序出现异常让事务回滚
int x = 1/0;
dao.update(target);
//提交事务
conn.commit();
flag = true;
}catch (Exception e) {
e.printStackTrace();
//出现异常以后就回滚事务
conn.rollback();
flag = false;
}finally{
conn.close();
}
return flag;
}
}
这样TextDao只负责CRUD,里面没有具体的业务处理方法了,职责就单一了,而TextService则负责具体的业务逻辑和事务的处理,须要操做数据库时,就调用TextDao层提供的CRUD方法操做数据库。
(3)使用ThreadLocal进行更加优雅的事务处理
注:ThreadLocal使用场合主要解决多线程中数据因并发产生不一致问题(解决线程安全)。ThreadLocal为每一个线程中并发访问的数据提供一个独立副本,副本之间相互独立(独立操做),这样每个线程均可以随意修改本身的变量副本,而不会对其余线程产生影响。经过访问副原本运行业务,这样的结果是耗费了内存,单大大减小了线程同步所带来性能消耗,也减小了线程并发控制的复杂度。
(ThreadLocal和Synchonized都用于解决多线程并发访问,synchronized是利用锁的机制,使变量或代码块在某一时该只能被一个线程访问。而ThreadLocal为每个线程都提供了变量的副本,使得每一个线程在某一时间访问到的并非同一个对象,这样就隔离了多个线程对数据的数据共享)
Synchronized用于线程间的数据共享,而ThreadLocal则用于线程间的数据隔离。
ThreadLocal类的使用范例以下:
public class ThreadLocalTest {
public static void main(String[] args) {
//获得程序运行时的当前线程
Thread currentThread = Thread.currentThread();
System.out.println(currentThread);
//ThreadLocal一个容器,向这个容器存储的对象,在当前线程范围内均可以取得出来
ThreadLocal<String> t = new ThreadLocal<String>();
//把某个对象绑定到当前线程上 对象以键值对的形式存储到一个Map集合中,对象的的key是当前的线程,如: map(currentThread,"aaa")
t.set("aaa");
//获取绑定到当前线程中的对象
String value = t.get();
//输出value的值是aaa
System.out.println(value);
}
}
1:使用ThreadLocal类进行改造数据库链接工具类JdbcUtils,改造后的代码以下:
/**
* @ClassName: JdbcUtils2
* @Description: 数据库链接工具类
* @author:
* @date:
*
*/
public class JdbcUtils2 {
private static ComboPooledDataSource ds = null;
//使用ThreadLocal存储当前线程中的Connection对象
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
//在静态代码块中建立数据库链接池
static{
try{
//经过代码建立C3P0数据库链接池
/*ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/jdbcstudy");
ds.setUser("root");
ds.setPassword("XDP");
ds.setInitialPoolSize(10);
ds.setMinPoolSize(5);
ds.setMaxPoolSize(20);*/
//经过读取C3P0的xml配置文件建立数据源,C3P0的xml配置文件c3p0-config.xml必须放在src目录下
//ds = new ComboPooledDataSource();//使用C3P0的默认配置来建立数据源
ds = new ComboPooledDataSource("MySQL");//使用C3P0的命名配置来建立数据源
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* @Method: getConnection
* @Description: 从数据源中获取数据库链接
* @Anthor:
* @return Connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
//从当前线程中获取Connection
Connection conn = threadLocal.get();
if(conn==null){
//从数据源中获取数据库链接
conn = getDataSource().getConnection();
//将conn绑定到当前线程
threadLocal.set(conn);
}
return conn;
}
/**
* @Method: startTransaction
* @Description: 开启事务
* @Anthor:
*
*/
public static void startTransaction(){
try{
Connection conn = threadLocal.get();
if(conn==null){
conn = getConnection();
//把 conn绑定到当前线程上
threadLocal.set(conn);
}
//开启事务
conn.setAutoCommit(false);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @Method: rollback
* @Description:回滚事务
* @Anthor:
*/
public static void rollback(){
try{
//从当前线程中获取Connection
Connection conn = threadLocal.get();
if(conn!=null){
//回滚事务
conn.rollback();
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @Method: commit
* @Description:提交事务
* @Anthor:
*/
public static void commit(){
try{
//从当前线程中获取Connection
Connection conn = threadLocal.get();
if(conn!=null){
//提交事务
conn.commit();
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @Method: close
* @Description:关闭数据库链接(注意,并非真的关闭,而是把链接还给数据库链接池)
* @Anthor:
*
*/
public static void close(){
try{
//从当前线程中获取Connection
Connection conn = threadLocal.get();
if(conn!=null){
conn.close();
//解除当前线程上绑定conn
threadLocal.remove();
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @Method: getDataSource
* @Description: 获取数据源
* @Anthor:
* @return DataSource
*/
public static DataSource getDataSource(){
//从数据源中获取数据库链接
return ds;
}
}
2:对TextDao进行改造,数据库链接对象再也不须要service层传递过来,而是直接从JdbcUtils2提供的getConnection方法去获取,改造后的TextDao以下:
/**
* @ClassName: TextDao
* @Description: 针对Account对象的CRUD
* @author:
* @date:
*
*/
public class TextDao2 {
public void update(Account account) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "update account set name=?,money=? where id=?";
Object params[] = {account.getName(),account.getMoney(),account.getId()};
//JdbcUtils2.getConnection()获取当前线程中的Connection对象
qr.update(JdbcUtils2.getConnection(),sql, params);
}
public Account find(int id) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "select * from account where id=?";
//JdbcUtils2.getConnection()获取当前线程中的Connection对象
return (Account) qr.query(JdbcUtils2.getConnection(),sql, id, new BeanHandler(Account.class));
}
}
3:对TextService进行改造,service层再也不须要传递数据库链接Connection给Dao层,改造后的TextService以下:
public class TextService2 {
/**
* @Method: transfer
* @Description:在业务层处理两个帐户之间的转帐问题
* @Anthor:
* @param sourceid
* @param tartgetid
* @param money
* @throws SQLException
*/
public boolean transfer(int sourceid,int tartgetid,float money) throws SQLException{
boolean flag = false;
try{
//开启事务,在业务层处理事务,保证dao层的多个操做在同一个事务中进行
JdbcUtils2.startTransaction();
TextDao2 dao = new TextDao2 ();
Account source = dao.find(sourceid);
Account target = dao.find(tartgetid);
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
dao.update(source);
//模拟程序出现异常让事务回滚
int x = 1/0;
dao.update(target);
//SQL正常执行以后提交事务
JdbcUtils2.commit();
flag = true;
}catch (Exception e) {
e.printStackTrace();
//出现异常以后就回滚事务
JdbcUtils2.rollback();
flag = false;
}finally{
//关闭数据库链接
JdbcUtils2.close();
}
return flag;
}
}
ThreadLocal类在开发中使用得是比较多的,程序运行中产生的数据要想在一个线程范围内共享,只须要把数据使用ThreadLocal进行存储便可。
(4)ThreadLocal + Filter 处理事务
ThreadLocal + Filter进行统一的事务处理,这种方式主要是使用过滤器进行统一的事务处理
一、编写一个事务过滤器TransactionFilter
/**
* @ClassName: TransactionFilter
* @Description:ThreadLocal + Filter 统一处理数据库事务
* @author:
* @date:
*
*/
public class TransactionFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
Connection connection = null;
try {
//一、获取数据库链接对象Connection
connection = JdbcUtils.getConnection();
//二、开启事务
connection.setAutoCommit(false);
//三、利用ThreadLocal把获取数据库链接对象Connection和当前线程绑定
ConnectionContext.getInstance().bind(connection);
//四、把请求转发给目标Servlet
chain.doFilter(request, response);
//五、提交事务
connection.commit();
} catch (Exception e) {
e.printStackTrace();
//六、回滚事务
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//req.setAttribute("errMsg", e.getMessage());
//req.getRequestDispatcher("/error.jsp").forward(req, res);
//出现异常以后跳转到错误页面
res.sendRedirect(req.getContextPath()+"/error.jsp");
}finally{
//七、解除绑定
ConnectionContext.getInstance().remove();
//八、关闭数据库链接
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public void destroy() {
}
}
2:咱们在TransactionFilter中把获取到的数据库链接使用ThreadLocal绑定到当前线程以后,在DAO层还须要从ThreadLocal中取出数据库链接来操做数据库,所以须要编写一个ConnectionContext类来存储ThreadLocal,ConnectionContext类的代码以下:
/**
* @ClassName: ConnectionContext
* @Description:数据库链接上下文
* @author:
* @date:
*/
public class ConnectionContext {
/**
* 构造方法私有化,将ConnectionContext设计成单例
*/
private ConnectionContext(){
}
//建立ConnectionContext实例对象
private static ConnectionContext connectionContext = new ConnectionContext();
/**
* @Method: getInstance
* @Description:获取ConnectionContext实例对象
* @Anthor:
* @return
*/
public static ConnectionContext getInstance(){
return connectionContext;
}
/**
* @Field: connectionThreadLocal
* 使用ThreadLocal存储数据库链接对象
*/
private ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<Connection>();
/**
* @Method: bind
* @Description:利用ThreadLocal把获取数据库链接对象Connection和当前线程绑定
* @Anthor:
* @param connection
*/
public void bind(Connection connection){
connectionThreadLocal.set(connection);
}
/**
* @Method: getConnection
* @Description:从当前线程中取出Connection对象
* @Anthor:
* @return
*/
public Connection getConnection(){
return connectionThreadLocal.get();
}
/**
* @Method: remove
* @Description: 解除当前线程上绑定Connection
* @Anthor:
*
*/
public void remove(){
connectionThreadLocal.remove();
}
}
3:在DAO层想获取数据库链接时,就可使用ConnectionContext.getInstance().getConnection()来获取,以下所示:
/**
* @ClassName: AccountDao
* @Description: 针对Account对象的CRUD
* @author:
* @date:
*
*/
public class TextDao3 {
public void update(Account account) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "update account set name=?,money=? where id=?";
Object params[] = {account.getName(),account.getMoney(),account.getId()};
//ConnectionContext.getInstance().getConnection()获取当前线程中的Connection对象
qr.update(ConnectionContext.getInstance().getConnection(),sql, params);
}
public Account find(int id) throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "select * from account where id=?";
//ConnectionContext.getInstance().getConnection()获取当前线程中的Connection对象
return (Account) qr.query(ConnectionContext.getInstance().getConnection(),sql, id, new BeanHandler(Account.class));
}
}
4:Service层也不用处理事务和数据库链接问题了,这些统一在TransactionFilter中统一管理了,Service层只须要专一业务逻辑的处理便可,以下所示:
public class TextService3 {
/**
* @Method: transfer
* @Description:在业务层处理两个帐户之间的转帐问题
* @Anthor:
* @param sourceid
* @param tartgetid
* @param money
* @throws SQLException
*/
public void transfer(int sourceid, int tartgetid, float money)
throws SQLException {
TextDao3 dao = new TextDao3 ();
Account source = dao.find(sourceid);
Account target = dao.find(tartgetid);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
dao.update(source);
// 模拟程序出现异常让事务回滚
int x = 1 / 0;
dao.update(target);
}
}
5:Web层的Servlet调用Service层的业务方法处理用户请求,须要注意的是:调用Service层的方法出异常以后,继续将异常抛出,这样在TransactionFilter就能捕获到抛出的异常,继而执行事务回滚操做,以下所示:
public class AccountServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { TextService3 service = new TextService3(); try { service.transfer(1, 2, 100); } catch (SQLException e) { e.printStackTrace(); //注意:调用service层的方法出异常以后,继续将异常抛出,这样在TransactionFilter就能捕获到抛出的异常,继而执行事务回滚操做 throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }