我在Java中有一个存储库,其选择方法基本上如下所示:
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();
}
}
我决定使用存储库模式。无论我查看的文档是什么,包括Eric Evan的《域驱动设计》一书或一些online articles,他们都将SQL语句视为String,并使用类似于String.format
的参数来填充参数。我认为PreparedStatement
更适合此目的。但是,如果在连接块内部创建并使用了PreparedStatement,该如何使用呢?