4

我有一个带有许多方法的 DAO 类,这些方法有很多重复的代码,如下所示: -

public void method1(...) {
  Connection conn = null;
  try {
      //custom code here
  } catch (SQLException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } catch (QueryNotFoundException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } finally {
     if (conn != null)
        connectionPool.returnConnection(conn);
  } 

public void method2(...) {
  Connection conn = null;
  try {
      //different custom code here
  } catch (SQLException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } catch (QueryNotFoundException e) {
     LOG.error("Error accessing the database.", e);
     throw new DatabaseException();
  } finally {
     if (conn != null)
        connectionPool.returnConnection(conn);
  } 

我想重组这个类,把try,catch,finally放在一个地方以避免重复。我将如何做到这一点?

4

4 回答 4

8

为 ex 创建一个接口。可执行文件:

 public interface Executable() {

   void exec() throws SqlException();

 }

将每个 dao 方法重构为:

public void method1() {
   execute(new Executable() {

     @Override
     public void exec() throws SqlException() {
          // your code here
     }
  });
  } 

在您的 DAO 中创建以下方法执行:

private void execute(Executor ex) {
    try {
      ex.exec();
    } catch(...) {
      ...
    } finally {
       ...
    }
}
于 2010-12-16T11:05:22.110 回答
2

我认为你应该使用的是Spring-JDBCJdbcTemplate

即使您不使用 spring 来管理您的应用程序,您也可以通过编程方式使用 JdbcTemplate 来抽象出所有的连接管理和错误处理。

示例代码:

List<Actor> actors = this.jdbcTemplate.query(
        "select first_name, last_name from t_actor",
        new RowMapper<Actor>() {
            public Actor mapRow(ResultSet rs, int rowNum)
            throws SQLException {
                Actor actor = new Actor();
                actor.setFirstName(rs.getString("first_name"));
                actor.setLastName(rs.getString("last_name"));
                return actor;
            }
        });

如您所见,您只处理实际查询,而不是围绕它的基础设施。

于 2010-12-16T11:05:50.897 回答
1

我会在这里使用AOP作为 commong 日志记录模式。例如:-

<bean id="exceptionLogger" class="my.good.ExceptionLogger" />  
    <aop:config>
            <aop:pointcut id="allDaoMethods" expression="execution(* my.dao.*(..))" />
            <aop:aspect id="daoLogger" ref="exceptionLogger">
                <aop:after-throwing pointcut-ref="allDaoMethods"
                                    method="logIt"
                                    throwing="e"/>
            </aop:aspect>  
    </aop:config>

ExceptionLogger 类可能如下所示:-

public class ExceptionLogger {
    private static Logger logger = Logger.getLogger(ExceptionLogger.class);
    public void logIt(JoinPoint jp, Exception e) {
        StringBuilder msg = new StringBuilder();
        msg.append("<whatever makes sense>");
        logger.error(msg.toString());
    }
}
于 2010-12-16T10:57:18.520 回答
0

这类似于没有匿名类的 Vladimir 解决方案,可能从这些方法返回值。

interface DaoOperation {
    void execute() throws SQLException;
}

class Operation1 implements DaoOperation {

    public void execute() {
        // former method1
    }
}

// in case you'd ever like to return value
interface TypedDaoOperation<T> {
    T execute() throws SQLException;
}

class Operation2 implements TypedDaoOperation<String> {
    public String execute() {
        return "something";
    }
}

class DaoOperationExecutor {
    public void execute(DaoOperation o) {
        try {
            o.execute();
        } catch (SQLException e) {
            // handle it as you want
        }
    }

    public <T>T execute(TypedDaoOperation<T> o) {
        try {
            return o.execute();
        } catch (SQLException e) {
            // handle it as you want
        }
    }
}
于 2010-12-16T11:24:07.333 回答