對於CRUD操作上的一個數據集,很高興使用中間表。這避免了大量的查詢被放置在大型數據集上。
給我的建議,以解決這個問題之前,我想指出,對數據庫結構的一些言論,我有:
- 的
total
領域顯然是一個計算的字段。這些信息並不適合放入數據庫。這是根據要求計算的。
- 整套數據顯然是文件(發票)的一部分。因此,數據庫中必須有一個字段,用於唯一標識與數據相關的文檔。
另外,我想說的是,這樣的決定是爲特定的數據庫做出的。在這種情況下,我的解決方案涉及mysql。
這是在其底部的代碼段運行
CREATE TABLE `invoice` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`invoice_id` int(10) unsigned NOT NULL,
`description` varchar(255) DEFAULT NULL,
`qty` double DEFAULT NULL,
`unitprice` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
表的DDL而這是使上使用文檔ID密鑰(invoce_id
)的數據集CRUD操作的代碼。
public boolean save(long invoice_id, List<Invoice> list) throws SQLException {
try(Connection connection = getConnection()) {
try {
connection.setAutoCommit(false);
String query =
"create temporary table if not exists `invoice_tmp` (" +
"`id` int(10) unsigned NOT NULL," +
"`description` varchar(255) DEFAULT NULL," +
"`qty` double DEFAULT NULL," +
"`unitprice` double DEFAULT NULL)";
connection.createStatement().executeUpdate(query);
query = "insert into `invoice_tmp` values (?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(query);
for(Invoice invoice: list) {
statement.setLong(1, invoice.getId());
statement.setString(2, invoice.getDescription());
statement.setDouble(3, invoice.getQty());
statement.setDouble(4, invoice.getUnitPrice());
statement.addBatch();
}
statement.executeBatch();
statement.close();
query =
"delete invoice from invoice " +
"left join invoice_tmp on (invoice.id = invoice_tmp.id) " +
"where invoice_id = ? and invoice_tmp.id is null";
statement = connection.prepareStatement(query);
statement.setLong(1, invoice_id);
statement.executeUpdate();
statement.close();
query =
"update `invoice` " +
"join `invoice_tmp` using (`id`) " +
"set " +
"`invoice`.description = `invoice_tmp`.description, " +
"`invoice`.qty = `invoice_tmp`.qty, " +
"`invoice`.unitprice = `invoice_tmp`.unitprice";
connection.createStatement().executeUpdate(query);
query =
"insert into `invoice` (`invoice_id`, `description`, `qty`, `unitprice`) " +
"select ? as `invoice_id`, `description`, `qty`, `unitprice` from `invoice_tmp` where `id` = 0";
statement = connection.prepareStatement(query);
statement.setLong(1, invoice_id);
statement.executeUpdate();
statement.close();
connection.createStatement().executeUpdate("drop table if exists `invoice_tmp`");
connection.commit();
return true;
}
catch (Exception e) {
connection.rollback();
throw e;
}
}
}
this是一個測試項目,演示了上述代碼如何工作。
你的問題是什麼? –
歡迎來到SO。所提供的信息不足以幫助您。嘗試打印'index'和'(String)tablesample.getValueAt(row,X)'。你可能會感到驚訝。 – c0der
我已經試着把索引:String sql =「更新發票SET描述=?,數量=?,單位價格=?」 +「,total =?WHERE id =」+ index;但唯一可以更新的是第一行,其他將與第一行相同 –