我正在尝试编写一种方法来检索数据库中的一行。大约有50%的时间将不存在该行。我尝试使用jdbcTemplate.queryForObject,但是如果数据库中不存在该行,则会导致引发异常。我认为尝试捕获该方法不是一种好的做法。
我读到,如果您的数据可能为空,那么jdbcTemplate.query是一个更好的选择。但是,只有返回列表,我才能使其正常运行。返回列表在这里实际上没有任何意义,因为我仅选择1行,该行可能存在或可能不存在。
public List<LoanDetailsBean> getLoanDetailsByInsaddr(String insaddr) {
String SQL_GET_LOAN_DETAILS_BY_INSADDR =
"SELECT TOP 1 cip.tranchesize, " +
" cip.maturitydate, " +
" cip.moodysissuerrating, " +
" cip.snpissuerrating, " +
" cip.moodysassetrating, " +
" cip.snpassetrating " +
"FROM cloinstrumentproperty cip " +
"WHERE insaddr = ? " +
"ORDER BY updatedtime DESC ";
return isdbJdbcTemplate.query(SQL_GET_LOAN_DETAILS_BY_INSADDR, new Object[] { insaddr }, (rs, rowNum) ->
new LoanDetailsBean(
rs.getDouble("tranchesize"),
rs.getString("maturitydate"),
rs.getString("moodysissuerrating"),
rs.getString("snpissuerrating"),
rs.getString("moodysassetrating"),
rs.getString("snpassetrating")
)
);
}
如何重新编写此代码以使其更有意义?
您的项目中是否可以使用第三方库?
这可以通过我自己的方法更简单地完成:
<dependency>
<groupId>com.github.buckelieg</groupId>
<artifactId>db-fn</artifactId>
<version>0.3.4</version>
</dependency>
然后:
public List<LoanDetailsBean> getLoanDetailsByInsaddr(String insaddr) {
try (DB db = new DB("jdbc:postgresql://host:port/database?user=user&password=pass")) {
return db.select("SELECT TOP 1 cip.tranchesize, cip.maturitydate, cip.moodysissuerrating, cip.snpissuerrating, cip.moodysassetrating, cip.snpassetrating FROM cloinstrumentproperty cip WHERE insaddr=? ORDER BY updatedtime DESC", insaddr)
.list(rs -> new LoanDetailsBean(rs.getDouble("tranchesize"), rs.getString("maturitydate"), rs.getString("moodysissuerrating"), rs.getString("snpissuerrating"), rs.getString("moodysassetrating"), rs.getString("snpassetrating"))));
}
}