有多種方法可以解決這個問題。這是一個快速和骯髒的只是顯示結果。您可以創建一個List
並將其添加到您的model
。
服務(爲MyService):
public static List createList(ResultSet resultSet) throws SQLException {
ResultSetMetaData metadata = resultSet.getMetaData();
int numberOfColumns = metadata.getColumnCount();
List<String> list = new ArrayList<>(numberOfColumns);
while (resultSet.next()) {
int i = 1;
while (i <= numberOfColumns) {
list.add(resultSet.getString(i++));
}
}
return list;
}
控制器:
@GetMapping("/myPage")
public String getList(Model model) {
ResultSet resultSet = ...; //however you call this
model.addAttribute("items", MyService.createList(resultSet); //try block hidden for brevity
return "myPage";
}
HTML(myPage.html下):
<div th:each="item : ${items}">
<span th:text="${item}">No item</span>
</div>
另一種(可以說更乾淨的)方法是使用執行器RowMapper
。我摘錄了一些代碼爲例:
public class EmployeeMapper implements RowMapper {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setEmpid(rs.getInt("empid"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setSalary(rs.getLong("salary"));
return employee;
}
}
那麼你可能有:
public Employee getEmployee(Integer empid) {
String SQL = "SELECT * FROM Employee WHERE empid = ?";
Employee employee = (Employee) jdbcTemplateObject.queryForObject(SQL, new Object[]{empid}, new EmployeeMapper());
return employee;
}
而且你可以將這些豆子添加到模型中,並如上重複。還有BeanPropertyRowMapper
用於快速實現Spring的RowMapper
。
雖然不是要與ResultSet
s此路線,你可能會更好用JPA實現,只是返回List
對象。這是更多的依賴關係,但最終維護的代碼更少。