【发布时间】:2023-03-22 14:44:01
【问题描述】:
这是java数据访问代码的好风格,还是最后尝试的太多了?
public List<Item> getItems() throws ItemException {
ArrayList<Item> items = new ArrayList<Item>();
try {
Connection con = ds.getConnection();
try {
PreparedStatement pStmt = con.prepareStatement("SELECT ....");
try {
ResultSet rs = pStmt.executeQuery();
try {
while (rs.next()) {
Item item = new Item();
item.setItemNo(rs.getString("item_id"));
// ...
items.add(item);
}
} finally {
rs.close();
}
} finally {
pStmt.close();
}
} finally {
con.close();
}
} catch (SQLException e) {
throw new ItemException(e);
}
return items;
}
【问题讨论】:
-
我建议你去冬眠。它有很多功能。 Aarons 代码看起来不错,但如果您每次都使用 JDBC。您最终将创建大量与数据库的连接,这可能会影响应用程序的性能。
-
ArrayList<Item> items = new ArrayList<Item>();应该是List<Item> items = new ArrayList<Item>();