动态网站制作指南 [  QQ表情  ]
[ 投票调查 ]
[ 企业邮箱 ]
[ 网站空间 ]
网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
ASP源码 | .Net源码 | PHP源码 | JSP源码 | JAVA源码 | CGI源码 | VB源码 | C++源码 | Delphi源码 | PB源码 | VF源码 | 汇编 | 服务器
Firefox | IE | Maxthon | 迅雷 | 电驴 | BitComet | FlashGet | QQ | QQ空间 | Vista | 输入法 | Ghost | Word | Excel | wps | Powerpoint
asp | .net | php | jsp | Sql | c# | Ajax | xml | Dreamweaver | FrontPages | Javascript | css | photoshop | fireworks | Flash | Cad | Discuz!
当前位置 > 网站建设学院 > 网络编程 > Java教程
Tag:注入,存储过程,分页,安全,优化,xmlhttp,fso,jmail,application,session,防盗链,stream,无组件,组件,md5,乱码,缓存,加密,验证码,算法,cookies,ubb,正则表达式,水印,索引,日志,压缩,base64,url重写,上传,控件,Web.config,JDBC,函数,内存,PDF,迁移,结构,破解,编译,配置,进程,分词,IIS,Apache,Tomcat,phpmyadmin,Gzip,触发器,socket
网络编程:ASP教程,ASP.NET教程,PHP教程,JSP教程,C#教程,数据库,XML教程,Ajax,Java,Perl,Shell,VB教程,Delphi,C/C++教程,软件工程,J2EE/J2ME,移动开发
文章搜索服务
邮件订阅
输入你的邮件地址,
你将不会错过任何关于:
[ Java教程 ]的信息

本月文章推荐
.javascript+xml实现二级下拉菜单.
.java 3D 动画场景编程简介.
.JBuilder2005 Servlet开发之自启.
.如何在Java应用程序中实现copy图.
.利用attributeGroup元素重用属性.
.use itext create a PDF file.
.Java规则引擎工作原理及其应用.
.EJB技术之旅(三).
.在Globus中的debug方法.
.可扩展的Java应用程序开发模式.
.Struts常见错误及原因分析.
.采用敏捷方法进行用户界面开发.
.J2ME MIDP开发综合实例.
.SCJP 考 试 大 纲.
.Jpetstore阅读心得之分层结构.
.推技术聊天室的实现(上).
.LN2 属性.
.MyEclipse 4.1 正式发.
.高级:使用异步Servlet扩展AJAX应.
.JAVA对象转为JavaString的几种常.

使用动态代理实现用AOP对数据库进行操作

发表日期:2008-3-14 |


要实现对数据库的操作,离不开数据源(DataSource)或者连接(Connection),但是通常来说对数据库的操作都应该放在DAO中,而DAO又不应该与应用服务器相关联,所以一般都使用连接(Connection)。现在我们这里就有一个问题了,怎么在拦截器中获得连接。我想可以通过两种方式获得:
在分别讨论这两种方法之前,我们需要先讨论一下在处理数据库的时候的异常的处理。我这里做了一个TransactionException继承至RuntimeException然后在拦截器里面抛出,再又应用框架处理这个异常。下面试这个类的代码:
public class TransactionException extends RuntimeException {
    private Throwable superException;
    private String myMessage;
    
    public TransactionException(Throwable throwable){
        super(throwable);
        this.superException = throwable;
    }
    
    public TransactionException(Throwable throwable,String message){
        super(message,throwable);
        this.superException = throwable;
        this.myMessage = message;
    }

    /**
     * @return Returns the myMessage.
     */
    public String getMessage() {
        return myMessage;
    }

    /**
     * @return Returns the superException.
     */
    public Throwable getSuperException() {
        return superException;
    }

    /**
     * @param myMessage The myMessage to set.
     */
    public void setMyMessage(String message) {
        this.myMessage = message;
    }

    /**
     * @param superException The superException to set.
     */
    public void setSuperException(Throwable superException) {
        this.superException = superException;
    }
    
    
}
1)    通过方法的第一个参数传进去
l    DAO
import java.sql.Connection;

public class TestDao {
    public void insertA(Connection con,String a,String b,……){
        …………………………………………
一系列操作
…………………………………………
    }
    
    public String queryA(Connection con,…….){
    …………………………………………
一系列操作
…………………………………………
}

    public void updateA(Connection con,…….){
        …………………………………………
一系列操作
…………………………………………
}
}

l    拦截器
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TransactionInterceptor implements Interceptor {

    public void before(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = (Connection) invInfo.getArgs()[0];
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                throw new TransactionException(e);
            }
        }
    }

    public void after(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = (Connection) invInfo.getArgs()[0];
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }

    public void exceptionThrow(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = (Connection) invInfo.getArgs()[0];
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }
    
    private List getNeedTransaction(){
        List needTransactions = new ArrayList();
        needTransactions.add("insert");
        needTransactions.add("update");
        return needTransactions;
    }
    
    private boolean isNeedTransactions(InvokeJniInfo invInfo){
        String needTransaction = "";
        List needTransactions = getNeedTransaction();
        for(int i = 0;i            needTransaction = (String)needTransactions.get(i);
            if(invInfo.getMethod().getName().startsWith(needTransaction)){
                return true;
            }
        }
        return false;
    }
}

需要注意的是:getNeedTransaction就是需要进行事务处理的方法的开头,这个方法可以写成一个从配置文件里面去读,这里我就写死在里面了。只是对insert和update开头的方法进行事务控制。
2)    将Connection对象放在ThreadLocal中
l    ConnectionUtil类:
import java.sql.Connection;

public final class ConnectionUtil {
    private static ThreadLocal connections = new ThreadLocal();
    public static Connection getConnection(){
        Connection conn = null;
        conn = (Connection) connections.get();
        if(conn == null){
            conn = getRealConnection();
            connections.set(conn);
        }
        return conn;
    }
    public static void realseConnection(Connection conn){
        connections.set(null);
    }
    private static Connection getRealConnection() {
        实现自己获取连接的代码
        return null;
    }
}
l    DAO类
public class TestDao {
    public void insertA(String a,String b){
        Connection conn = getConnection();
        …………………………………………
一系列操作
…………………………………………
    }
        public String queryA(Connection con,…….){
        Connection conn = getConnection();
    …………………………………………
一系列操作
…………………………………………
}

    public void updateA(Connection con,…….){
Connection conn = getConnection();
        …………………………………………
一系列操作
…………………………………………
}

    private Connection getConnection(){
        return ConnectionUtil.getConnection();
    }
    
}
l    拦截器
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TransactionInterceptor implements Interceptor {

    public void before(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = getConnection();
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                throw new TransactionException(e);
            }
        }
    }

    public void after(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = getConnection();
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                        releaseConnection(conn);
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }

    public void exceptionThrow(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = getConnection();
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                        releaseConnection(conn);
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }
    
    private Connection getConnection(){
        return ConnectionUtil.getConnection();
    }
    
    private void releaseConnection(Connection conn){
        ConnectionUtil.releaseConnection(conn);
    }
    private List getNeedTransaction(){
        List needTransactions = new ArrayList();
        needTransactions.add("insert");
        needTransactions.add("update");
        return needTransactions;
    }
    
    private boolean isNeedTransactions(InvokeJniInfo invInfo){
        String needTransaction = "";
        List needTransactions = getNeedTransaction();
        for(int i = 0;i            needTransaction = (String)needTransactions.get(i);
            if(invInfo.getMethod().getName().startsWith(needTransaction)){
                return true;
            }
        }
        return false;
    }
}
    最后将这个拦截器添加到AOP拦截框架中去,InterceptorHandler类中的getIntercetors方法中添加一个:

    private synchronized List getIntercetors(){
        if(null == interceptors){
            interceptors = new ArrayList();
            ……………………………………
interceptors.add(new TransactionInterceptor ());
            ……………………………………
        }
        return interceptors;
}

到此全部ok!
上一篇:Java入门-漫谈Java程序的性能优化 人气:579
下一篇:Java基础知识:谈谈简单Hibernate入门 人气:433
浏览全部java的内容 Dreamweaver插件下载 常用网页广告代码全集
  最新网站源码 最新软件下载
2008-9-6 Movie34电影搜索引擎 v3.0
2008-9-6 wap2.0仿帝国建站喜用 v2.0
2008-9-6 免费人才招聘网 宽屏版 v3.01
2008-9-6 喜喔喔视频采集程序 v1.0 beta
2008-9-6 ASP客户管理系统
2008-9-6 主流驿站中秋祝福程序
2008-9-6 php实现msn协议的类
2008-9-5 Coppermine Photo Gallery v1.4.
2008-9-5 清松网络日记本 v2.4
2008-8-23 Mini WinMount V0.4
2008-8-23 Vista优化大师3.11正式版
2008-8-23 Wine 1.13
2008-8-23 KlipFolio 5.0 Build 5899-80
2008-8-23 Windows Sysinternals Desktops
2008-8-23 OneTap Movies1.2破解版
2008-8-23 AnnotaterPDF阅读1.1.503 破解版
2008-8-23 SoundMeter分贝测量仪 v1.0汉化破
2008-8-23 iDrum音乐节拍1.0破解版
  发表评论
姓 名: 验证码:
内 容:
站长工具:网站收录查询 | Google PR查询 | ALEXA排名查询 | CSS在线编辑器 | 广告代码 | Html转换js | js/vbs加密 | md5加密 | 进制转换
实用工具:汉字翻译拼音 | 符号对照表 | 个税计算 | 经典小工具 | 汉字简繁转换 | 普通单位换算 | 公制单位换算 | 生辰老黄历 | 国内电话区号 国家代码与域名缩写 | 文字加密解密 | 健康查询 | 万年历 | 汉字横竖排版 | 手机号码查询 | 计算器 | ip搜索
业务联系 | 广告刊登 | 频道合作 | 投稿荐稿 | 联系方式 | 加入收藏 | RSS订阅
Copyright © 2000-2008 www.knowsky.com All rights reserved | 网络实名:动态网站制作指南 | 沪ICP备05001343号