我有這段代碼,非常標準的東西。它發生在一個Java對象一些過濾器,並返回所有記錄匹配過濾器:我可以將此模式用於where子句的可選部分嗎?
class MarkFilters {
Integer idFilter;
Integer userIDFilter;
Integer claimIDFilter;
}
List<Integer> findMarksMatchingFilters(MarkFilters filters) {
String sql = "select id from Mark where 1";
// This has the values to substitute in for the ?'s in the SQL
List<Object> parameters = new LinkedList<Object>();
if (filters.idFilter != null) {
sql += " and id = ?";
parameters.add(filters.idFilter);
}
if (filters.userIDFilter != null) {
sql += " and userID = ?";
parameters.add(filters.userIDFilter);
}
if (filters.claimIDFilter != null) {
sql += " and claimID = ?";
parameters.add(filters.claimIDFilter);
}
return executeSQLWithParameters(sql, parameters);
}
我找到了一種方法應該做同樣的事情:
List<Integer> findMarksMatchingFilters(MarkFilters filters) {
return executeSQLWithParameters(
"select * from Mark " +
"where (? = NULL or id = ?) " +
"and (? = NULL or userID = ?) " +
"and (? = NULL or claimID = ?) ",
filters.idFilter, filters.idFilter,
filters.userIDFilter, filters.userIDFilter,
filters.claimIDFilter, filters.claimIDFilter);
}
因此,舉例來說,如果我飼料在一個新MarkFilters(NULL,NULL,3),SQL語句將是:
select * from Mark
where (NULL = NULL or id = NULL)
and (NULL = NULL or userID = NULL)
and (3 = NULL or claimID = 3)
將理論上被優化以:
select * from Mark where claimID = 3;
我的具體問題:這種優化是否真的會發生?
我的更廣泛的問題:這是一個好模式,還是有缺點我看不到?
謝謝!
織補,害怕這一點。所以我想下一步就是讓我試試看看它們是否有類似的運行時間。 – Verdagon 2013-04-23 02:48:51