网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
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中文乱码解决方案和经验.
.有状态会话 bean运行结束时应及时.
.使用 Struts portlet 实现页面导.
.JCP失去活力 Java.net能否取而代.
.PDF背景灰色图片设定方法.
.Turbine HowTo 之 Service.
.classpath详解(谨献给那些找不到.
.用JCE共享Java密钥.
.Java 6中新型模态对话框API解析(.
.Think in java读书笔记.
.Josephus算法的JAVA语言实现.
.一些错误地解决方法.
.试试看把XML转成PDF的有效工具:.
.2005 Java中国开发者大会现场报道.
.敏捷开发的必要技巧:将注释转为.
.教您如何解决J2ME开发中的连续按.
.JAVA生成JPG缩略图.
.全面挖掘Java Excel API 使用方法.
.Struts入门经验.
.用状态栏提示改善JavaGUI.

使用动态代理实现用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程序的性能优化 人气:845
下一篇:Java基础知识:谈谈简单Hibernate入门 人气:600
浏览全部java的内容 Dreamweaver插件下载 网页广告代码 祝你圣诞节快乐 2009年新年快乐