gpt4 book ai didi

Java:如何保持三个对象之间的关系

转载 作者:行者123 更新时间:2023-11-30 11:25:06 25 4
gpt4 key购买 nike

我希望存储三个对象之间的关系列表,其中两个相关对象将各自仅存在于列表中的一个关系中,第三个是我可以递增的计数。它不是很普遍的 SO,但你可以在这里看到我在做什么

    public class Transaction implements AutoCloseable {
private final Connection conn;
private final Map<String, Map.Entry<PreparedStatement, Integer>> sts = new HashMap<>();

Transaction(final Connection conn) throws SQLException {
conn.setAutoCommit(false);
this.conn = conn;
}

<T> void batch(final String st, final List<T> ts,
final BatchingInstructions<T> bi) throws SQLException {
final PreparedStatement stat;
int counter;

// if statement has already been created, retrieve statement and batch count
if (sts.containsKey(st)) {
final Map.Entry<PreparedStatement, Integer> m = sts.get(st);
stat = m.getKey();
counter = m.getValue();
} else {
// else create statement and batch count
stat = conn.prepareStatement(getInsert(st));
counter = 0;
sts.put(st, // Can't do a new Map.Entry, really
}

for (final T t : ts) {
bi.batch(stat, t);
stat.addBatch();
// increment how many times a batch has been added to the statement.
// execute batch if necessary.
if (++counter > 5000) {
stat.executeBatch();
}
}

}

@Override
public void close() throws Exception {
for (final Map.Entry<PreparedStatement, Integer> m : sts.values()) {
if (m.getValue() > 0) {
m.getKey().executeBatch();
}
m.getKey().close();
}
conn.commit();
}

Guava 的表不能正常工作,并且 Map<String, Map<Statement, Integer>>也不是理想的,并且由于需要增加其中一个值而变得复杂(尽管为此我可能会使用此处找到的 mutableInt 解决方案 Most efficient way to increment a Map value in Java )。

我想知道是否有人知道这个问题的任何直接解决方案,可能在第三方库中?


使用已接受的答案,我能够让新类(class)做许多其他有用的事情。

class BatchPreparedStatement implements AutoCloseable {
private final PreparedStatement st;
private int counter = 0;

BatchPreparedStatement(final PreparedStatement st) {
this.st = st;
}

<T> void addBatch(final BatchingInstructions<T> bi, final T t)
throws SQLException {
bi.batch(st, t);
st.addBatch();
executeBatch(10000);
}

void executeBatch(final int count) throws SQLException {
if (counter++ > count) {
st.executeBatch();
counter = 0;
}
}

void finished() throws SQLException {
executeBatch(0);
}

@Override
public void close() throws Exception {
st.close();
}
}

最佳答案

你为什么不创建一个类来保存语句、计数和处理所有 addBatching 以及其他杂项 Activity 。

class BatchPreparedStatementHolder {

private int batchCount;
private PreparedStatement ps;

public BatchPreparedStatementHolder(PreparedStatement statement){
batchCount = 0;
ps = statment;
}

public void addBatch(){
ps.addBatch();
// increment how many times a batch has been added to the statement.
// execute batch if necessary.
if (++batchCount> 5000) {
ps.executeBatch();
batchCount = 0;
}
}

....

}

关于Java:如何保持三个对象之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com