【发布时间】:2016-04-12 06:49:15
【问题描述】:
偶然看到讲师提供的这段示例代码,并注意到一些奇怪的事情:在执行新的插入查询之前必须清空数据库中的数据(我假设避免数据库中的冗余数据)。
有什么办法可以避免这种通过 hashmap 向数据库插入数据的迂回方式?
public void saveCustomers() throws ClassNotFoundException, SQLException {
Statement statement = connection.createStatement();
String query = "delete from customer";
statement.executeUpdate(query);
Iterator customers = HRMS.Customers.entrySet().iterator();
while (customers.hasNext()) {
Customer customer;
Map.Entry customerMap = (Map.Entry) customers.next();
customer = (Customer) customerMap.getValue();
query = "insert into customer (memberId, name, nicn, gender, contact) "
+ "values ('" + customer.getMemberId() + "', '" + customer.getName() + "',"
+ " '" + customer.getId() + "', '" + customer.getGender().toString() + "', '" + customer.getContact() + "');";
statement.executeUpdate(query);
}
}
编辑:清除HashMap 并将数据同时插入数据库(可能使用不同的线程)会有所改进吗?
【问题讨论】:
-
使用唯一键怎么样?
-
这是一个使用 JDBC 的可怕例子。资源泄露、SQL 注入、...
-
@Matthias 这有很多问题。如果他支付了这次讲座的费用,OP 可能想要求退还他的钱。
-
那段代码太难闻了!但是,如果没有更多的上下文和对正在发生的事情的了解,实际上不可能决定是否应该缓存更新。这是一个基本的计算机科学问题:缓存以牺牲一致性为代价来加快速度,如果在缓存与底层存储不匹配时出现故障,那么您就有问题了。有人曾经说过“软件开发中最难的两件事是缓存一致性、命名事物和非一个错误”
-
使用 HashMap 缓存数据库查询是一个半心半意的解决方案。在同一台计算机上运行的数据库会更好地缓存自身。它是 O/R,Object-Relational 映射是一种缓存,但这是另一个层次。