diff --git a/src/main/java/org/casbin/adapter/JDBCBaseAdapter.java b/src/main/java/org/casbin/adapter/JDBCBaseAdapter.java index 008a6cd..c8e25ad 100644 --- a/src/main/java/org/casbin/adapter/JDBCBaseAdapter.java +++ b/src/main/java/org/casbin/adapter/JDBCBaseAdapter.java @@ -272,53 +272,8 @@ public void savePolicy(Model model) { try (Statement statement = conn.createStatement(); PreparedStatement ps = conn.prepareStatement(addSql)) { statement.execute(cleanSql); - for (Map.Entry entry : model.model.get("p").entrySet()) { - String ptype = entry.getKey(); - Assertion ast = entry.getValue(); - - for (List rule : ast.policy) { - CasbinRule line = savePolicyLine(ptype, rule); - - ps.setString(1, line.ptype); - ps.setString(2, line.v0); - ps.setString(3, line.v1); - ps.setString(4, line.v2); - ps.setString(5, line.v3); - ps.setString(6, line.v4); - ps.setString(7, line.v5); - - ps.addBatch(); - if (++count == batchSize) { - count = 0; - ps.executeBatch(); - ps.clearBatch(); - } - } - } - - for (Map.Entry entry : model.model.get("g").entrySet()) { - String ptype = entry.getKey(); - Assertion ast = entry.getValue(); - - for (List rule : ast.policy) { - CasbinRule line = savePolicyLine(ptype, rule); - - ps.setString(1, line.ptype); - ps.setString(2, line.v0); - ps.setString(3, line.v1); - ps.setString(4, line.v2); - ps.setString(5, line.v3); - ps.setString(6, line.v4); - ps.setString(7, line.v5); - - ps.addBatch(); - if (++count == batchSize) { - count = 0; - ps.executeBatch(); - ps.clearBatch(); - } - } - } + count = saveSectionPolicyWithBatch(model, "p", ps, count); + count = saveSectionPolicyWithBatch(model, "g", ps, count); if (count != 0) { ps.executeBatch(); @@ -336,6 +291,39 @@ public void savePolicy(Model model) { }); } + /** + * saveSectionPolicyWithBatch saves section policy rules to the storage. + * as a helper function for savePolicy + * only when the batchCount exceeds the batchSize will the actual save operation be performed + */ + private int saveSectionPolicyWithBatch(Model model, String section, PreparedStatement ps, int batchCount) throws SQLException { + if (!model.model.containsKey(section)) return batchCount; + for (Map.Entry entry : model.model.get(section).entrySet()) { + String ptype = entry.getKey(); + Assertion ast = entry.getValue(); + + for (List rule : ast.policy) { + CasbinRule line = savePolicyLine(ptype, rule); + + ps.setString(1, line.ptype); + ps.setString(2, line.v0); + ps.setString(3, line.v1); + ps.setString(4, line.v2); + ps.setString(5, line.v3); + ps.setString(6, line.v4); + ps.setString(7, line.v5); + + ps.addBatch(); + if (++batchCount == batchSize) { + batchCount = 0; + ps.executeBatch(); + ps.clearBatch(); + } + } + } + return batchCount; + } + /** * addPolicy adds a policy rule to the storage. */