我一直在设计一些源代码,因为我们的项目中有很多代码在进行 SQL 查询时被重复。
所以我做了下面的代码,尝试类似于命令模式的东西似乎工作得很好。它仅接收字符串中的 SQL 查询以及要在语句上设置的一些参数(如果需要)。因此,您可以将此代码用作匿名类,并执行查询,仅定义如何处理查询的输出。
我的问题是,我想设计这个来强制在匿名子类中定义和编写方法 getResult ,但我想不出在不创建抽象方法和类的情况下有任何方法可以做到这一点。
如果 QueryCommand 变得抽象,我应该创建另一个能够实例化的类,该类也不能是抽象的。还有其他方法可以强制子类中的重写吗?我正在寻找最聪明、最简单的方法来实现它。
不知道如何搜索类似的模式或解决方案。
提前致谢。
源代码:
import java.sql.Connection;
import java.sql.SQLException;
public interface IQueryCommand<T> {
T executeQuery(Connection conn, String query, Object... args) throws SQLException;
}
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import org.apache.log4j.Logger;
public class QueryCommand<T> implements IQueryCommand<T> {
private Logger LOGGER = Logger.getLogger(this.getClass());
/** The constant ERROR_CLOSING_RESULT_SET */
protected static final String ERROR_CLOSING_RESULT_SET = "Error when closing ResultSet";
/** The Constant ERROR_CLOSING_PREPARED_STATEMENT. */
protected static final String ERROR_CLOSING_PREPARED_STATEMENT = "Error when closing PreparedStatement";
// FIXME: I want this method to be mandatory to be defined in the anonymous child class
protected T getResult(ResultSet rs) throws SQLException {
return null;
};
public T executeQuery(Connection conn, String sqlQuery, Object... args) throws SQLException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(sqlQuery);
}
PreparedStatement ps = null;
ps = conn.prepareStatement(sqlQuery);
return executeQuery(conn, ps, args);
}
public T executeQuery(Connection conn, PreparedStatement ps, Object... args) throws SQLException {
ResultSet rs = null;
try {
if(args != null && args.length > 0) {
for(int i=0; i< args.length; i++) {
setArg(ps, i+1, args[i]);
}
}
rs = ps.executeQuery();
T result = getResult(rs); // Method defined in child class
return result;
} catch (SQLException e) {
throw e;
} finally {
if(rs != null) {
try {
rs.close();
} catch (final SQLException e) {
LOGGER.error(ERROR_CLOSING_RESULT_SET, e);
}
}
if (ps != null) {
try {
ps.close();
} catch (final Exception e) {
if(ps instanceof CallableStatement) {
LOGGER.error("Error when closing CallableStatement", e);
} else if(ps instanceof PreparedStatement) {
LOGGER.error(ERROR_CLOSING_PREPARED_STATEMENT, e);
}
}
}
}
}
/**
* Sets a value on the PreparedStatemente with a method dependending on dataType
*
* @param ps the preparedStatement
* @param idx the index on which the value is set
* @param value the value to set
* @throws SQLException if an error is detected
*/
private void setArg(PreparedStatement ps, int idx, Object value) throws SQLException {
// Implementation not relevant...
}
}
如何使用它的示例:
sqlQuery = " SELECT X FROM Y WHERE countryId = ? and languageId = ?";
return new QueryCommand<String>() {
// This method should be REQUIRED when compiling
@Override
protected String getResult(ResultSet rs) throws SQLException {
String result = "";
while (rs.next()) {
result = rs.getString("DESCRIPTION");
}
return result;
};
}.executeQuery(getDB2Connection(), sqlQuery.toString(), new Object[] { countryIdParameter, languageIdParameter});
最佳答案
I can't think any way of doing it without making an abstract method and class.
抽象类正是您需要的机制
I should make another class to be able to instantiate, which can't be abstract as well.
这是不正确的:匿名类完全能够继承抽象类,甚至扩展接口(interface),当然,前提是它们实现了所有抽象方法:
public class AbstractQueryCommand<T> implements IQueryCommand<T> {
abstract protected String getResult(ResultSet rs) throws SQLException;
...
}
return new AbstractQueryCommand<String>() {
@Override
protected String getResult(ResultSet rs) throws SQLException {
String result = "";
while (rs.next()) {
result = rs.getString("DESCRIPTION");
}
return result;
};
}
关于Java - 如何在子匿名类中强制重写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805937/