jeudi 11 juin 2020

Using PreparedStatement with Repository Pattern

I have a repository in Java that its select method basically looks like this:

public Map<String, Person> getPersons(Community community, long membership) {
    NationCode nationCode = community.getNation().getCode();
    DateTime endTime = DateTime.now();
    DateTime startTime = endTime.minusSeconds(runPeriod);
    RDSConnector connector = shardManager.getConnector(nationCode, membership);
    Map<String, Person> Persons = new HashMap<>();
    try (Connection connection = connector.getConnection()) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(QUERY_SOCIETY_BY_COMMUNITY)) {
            preparedStatement.setString(1, nationCode.getValue());
            preparedStatement.setString(2, community.getId());
            preparedStatement.setTimestamp(3, endTime.getMillis());
            preparedStatement.setTimestamp(3, startTime.getMillis());
            preparedStatement.setTimestamp(3, startTime.minusDays(10).getMillis());
            preparedStatement.executeQuery();
            ResultSet rs = preparedStatement.getResultSet();
            if(!rs.next()) {
                return null;
            }
            rs.beforeFirst();
            while (rs.next()) {
                String personId = rs.getString("p.person_id");
                String personName = rs.getString("p.personName");
                String communityLocation = rs.getString("c.location");
                persons.computeIfAbsent(personId, (k) -> new Person(personId, personName, communityLocation));
            }
            return persons;
        }
    } catch (SQLException ex) {
        throw new RuntimeException();
    }
}

I decided to use Repository pattern. Whatever doc I looked at, including Eric Evan's Domain Driven Design book, or some online articles, they treated the SQL statement as a String, and used something similar to String.format to fill in the parameters. I think PreparedStatement is more suited for this purpose. But how can I use PreparedStatement if it is created and used inside the connection block?

Aucun commentaire:

Enregistrer un commentaire