虽然这似乎是一个非常简单的问题,但我想出的唯一解决方案如下,对于时间复杂度较低的不那么难看的东西有什么建议吗?
我的应用程序在 Java 中,并且正在使用 MS-sql DB 进行检索skife.jdbi
。
假设我有一个Table
with columns A
, B
, and C
whereA
并B
形成一个主键。我想检索C
给定一个特别的A
and B
。这很容易实现。但是如果我对吞吐量的要求很高,所以我想Select
分批做这些语句。我最终得到如下内容:
给定 aSet
的Objects
值A
and B
,我迭代 List 编译所有A
and的值B
。然后我运行一个查询,如SELECT A, B, C FROM tbl WHERE A IN :listOfAs AND B IN :listOfBs
. A
然后我迭代查询的结果,通过比较和B
值将结果与原始对象匹配。这听起来很合理,但代码最终看起来像下面这样,看起来丑陋和次优?
class MyObject {
String A;
String B;
String C;
Object otherData;
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (!(other instanceof MyObject)) {
return false;
} else {
return A.equals(other.A) && B.equals(other.B);
}
}
@Override
public int hashCode() {
return 31 * A.hashCode() + B.hashCode();
}
}
// populates the of objects with their proper C value
void retrieveC(Set<MyObject> input) {
Set<String> aValues = new HashSet<>();
Set<String> bValues = new HashSet<>();
for (MyObject object : input) {
aValues.add(object.A);
bValues.add(object.B);
}
// the dao executes the query mentioned above, and returns a Set of
// MyObject instances with members A, B, and C populated from the results.
// Any results that do not contain a value for A, B, and C (which
// shouldn't exit) are filtered out by the dao.
Set<MyObject> results = dao.selectC(aValues, bValues);
// ewww... O(n^2)
for (MyObject object : input) {
boolean resultFound = false;
for (MyObject result : results) {
if (object.equals(result)) {
object.C = result.C;
resultFound = true;
break;
}
}
if (!resultFound) {
// handle this case
}
}
}