26 * POSSIBILITY OF SUCH DAMAGE. |
26 * POSSIBILITY OF SUCH DAMAGE. |
27 * |
27 * |
28 */ |
28 */ |
29 package de.uapcore.lightpit.dao; |
29 package de.uapcore.lightpit.dao; |
30 |
30 |
31 import java.sql.Date; |
31 import java.sql.*; |
32 import java.sql.PreparedStatement; |
32 import java.util.ArrayList; |
33 import java.sql.SQLException; |
33 import java.util.List; |
34 import java.sql.Types; |
|
35 import java.util.Optional; |
34 import java.util.Optional; |
36 import java.util.function.Function; |
35 import java.util.function.Function; |
37 |
36 |
38 /** |
37 /** |
39 * Some DAO utilities. |
38 * Some DAO utilities. |
63 } else { |
62 } else { |
64 stmt.setInt(index, key); |
63 stmt.setInt(index, key); |
65 } |
64 } |
66 } |
65 } |
67 |
66 |
|
67 @FunctionalInterface |
|
68 public interface ResultSetMapper<T> { |
|
69 T apply(ResultSet rs) throws SQLException; |
|
70 } |
|
71 |
|
72 public static <T> List<T> list(PreparedStatement stmt, ResultSetMapper<T> mapper) throws SQLException { |
|
73 List<T> results = new ArrayList<>(); |
|
74 try (var result = stmt.executeQuery()) { |
|
75 while (result.next()) { |
|
76 final var project = mapper.apply(result); |
|
77 results.add(project); |
|
78 } |
|
79 } |
|
80 return results; |
|
81 } |
|
82 |
|
83 public static <T> T find(PreparedStatement stmt, ResultSetMapper<T> mapper) throws SQLException { |
|
84 try (var result = stmt.executeQuery()) { |
|
85 if (result.next()) { |
|
86 final var ent = mapper.apply(result); |
|
87 return ent; |
|
88 } else { |
|
89 return null; |
|
90 } |
|
91 } |
|
92 } |
|
93 |
68 private Functions() { |
94 private Functions() { |
69 |
95 |
70 } |
96 } |
71 } |
97 } |