src/main/java/de/uapcore/lightpit/dao/AbstractDao.java

changeset 38
cf85ef18f231
parent 34
824d4042c857
child 39
e722861558bb
--- a/src/main/java/de/uapcore/lightpit/dao/AbstractDao.java	Sun May 10 10:58:31 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/dao/AbstractDao.java	Mon May 11 19:09:06 2020 +0200
@@ -28,24 +28,65 @@
  */
 package de.uapcore.lightpit.dao;
 
-import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Types;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
+import java.util.function.Function;
 
 public abstract class AbstractDao<T> implements GenericDao<T> {
 
-    protected abstract PreparedStatement listQuery(Connection connection) throws SQLException;
+    private final PreparedStatement listQuery;
+
+    protected AbstractDao(PreparedStatement listQuery) {
+        this.listQuery = listQuery;
+    }
+
+    public final T mapColumns(ResultSet result) throws SQLException {
+        return mapColumns(result, "");
+    }
+
+    public abstract T mapColumns(ResultSet result, String qualifier) throws SQLException;
 
-    protected abstract T mapColumns(ResultSet result) throws SQLException;
+    /**
+     * Qualifies a column label if an qualifier is specified.
+     *
+     * @param qualifier an optional qualifier
+     * @param label     the column label
+     * @return the label, qualified if necessary
+     */
+    protected final String qual(String qualifier, String label) {
+        if (qualifier == null || qualifier.isBlank()) {
+            return label;
+        } else {
+            return qualifier + "." + label;
+        }
+    }
+
+    protected final void setStringOrNull(PreparedStatement stmt, int index, String str) throws SQLException {
+        if (str == null || str.isBlank()) {
+            stmt.setNull(index, Types.VARCHAR);
+        } else {
+            stmt.setString(index, str);
+        }
+    }
+
+    protected final <T> void setForeignKeyOrNull(PreparedStatement stmt, int index, T instance, Function<T, Integer> keyGetter) throws SQLException {
+        Integer key = Optional.ofNullable(instance).map(keyGetter).orElse(null);
+        if (key == null) {
+            stmt.setNull(index, Types.INTEGER);
+        } else {
+            stmt.setInt(index, key);
+        }
+    }
 
     @Override
-    public List<T> list(Connection conn) throws SQLException {
+    public List<T> list() throws SQLException {
         List<T> list = new ArrayList<>();
-        try (PreparedStatement stmt = listQuery(conn);
-             ResultSet result = stmt.executeQuery()) {
+        try (ResultSet result = listQuery.executeQuery()) {
             while (result.next()) {
                 list.add(mapColumns(result));
             }

mercurial