'How do I use different ResultSet methods based on generic type from class in Java
I have an sqlite database with a table 'parts' that contains the column 'part'. This 'part' can be one of two things:
- String
- byte[] representing the bytes of an image
At one point in my java-program I need to fetch multiple 'parts' from the database and put them in a list. This is how I did it:
private ArrayList<String> getTextPart(String id) throws SQLException {
String sql = "SELECT part FROM parts WHERE question_id = " + id + " ORDER BY part_id";
ArrayList<String> parts = new ArrayList<>();
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
parts.add(rs.getString("part"));
}
return parts;
}
}
private ArrayList<byte[]> getImagePart(String id) throws SQLException {
String sql = "SELECT part FROM parts WHERE question_id = " + id + " ORDER BY part_id";
ArrayList<byte[]> parts = new ArrayList<>();
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
parts.add(rs.getBytes("part"));
}
return parts;
}
}
Now the only difference between these two methods is the making of the ArrayList:
ArrayList<String> parts = new ArrayList<>();
ArrayList<byte[]> parts = new ArrayList<>();
and the method called on the resultset:
parts.add(rs.getString("part"));
parts.add(rs.getBytes("part"));
I thinks this is needless code duplication, but i can't seem to find a way to fix it. I have tried to make a generic 'partFetcher' class, like so:
public class PartFetcher<T> {
private ArrayList<T> getPart(String id, Connection connection) throws SQLException {
String sql = "SELECT part FROM parts WHERE question_id = " + id + " ORDER BY part_id";
ArrayList<T> parts = new ArrayList<>();
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
parts.add(rs.???);
}
return parts;
}
}
}
But I have no idea what to to call from the ResultSet when adding to the list.
So my question is:
How can a make PartFetcher<String> call resultSet.getString("part")
and PartFetcher<byte[]> resultSet.getBytes("part")
or is there a known pattern to solve these kinds of problems?
(sidenote: I have no control over how the database looks, so splitting the parts into TextParts and ImageParts is not possible)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
