如何通过Stream做到这一点?我真的不知道如何,如果有人帮助我会很感激
public <C extends Collection<?>> int save(C items) {
log.info("Collection entering for save in the DB :_" + items.getClass() + " with size :_" + items.size());
int rowsAffected = 0;
if (!items.isEmpty()) {
try (Connection connection = DBConnectionManager.getConnection()) {
for (Object item : items) {
String query = queryBuilder(item);
try {
if (Model.class.isAssignableFrom(item.getClass())) {
PreparedStatement stmt = connection.prepareStatement(query);
stmt = fillStatement(item, stmt);
rowsAffected += stmt.executeUpdate();
} else {
log.info("Item _:" + item.getClass().getSimpleName()
+ "...");
}
} catch (SQLException e) {
log.error(e);
}
}
return rowsAffected;
} catch (SQLException e) {
log.error(e);
}
}
答案 0 :(得分:4)
看到您的代码后,我真的不认为Streams
会使其更具可读性,但是看到以下代码片段可以简化您的方法:
public int save(Collection<? extends Model> items) {
log.info("Collection entering for save in the DB :_" + items.getClass() + " with size :_" + items.size());
if (items.isEmpty()) {
return 0;
}
int rowsAffected = 0;
try (Connection connection = DBConnectionManager.getConnection()) {
for (Model item : items) {
String query = queryBuilder(item);
try(PreparedStatement stmt = connection.prepareStatement(query),
stmt = fillStatement(item, stmt)) {
rowsAffected += stmt.executeUpdate();
} catch (SQLException e) {
log.error(e);
}
}
} catch (SQLException e) {
log.error(e);
}
return rowsAffected;
}
C
不会执行任何操作Model.class.isAssignableFrom
仅接受模型。 “保存” collection
一半的模型和其他一半的东西是没有意义的。在此之前将它们分开。return
语句0
为空,则直接返回items
由于您已经将查询String
的创建和PreparedStatement
的填充工作外包了,因此您还可以将该部分提取到另一种方法中,然后在{{1}中使用}:
Stream
然后可以流式传输:
private int saveItem(Model item, Connection connection){
String query = queryBuilder(item);
try(PreparedStatement stmt = connection.prepareStatement(query),
stmt = fillStatement(item, stmt)) {
return stmt.executeUpdate();
} catch (SQLException e) {
log.error(e);
return 0;
}
}