2017-05-30 3 views
0

ResultSetからthymeleafを使用して属性を表示したいとします。thymeleafでResultSetをブラウズするには?

例: 私はthymeleafを使用して関数の結果を表示したいと思います。

public ResultSet getIntervenantById(String nomTable, String id,String nomcle) { 

     try { 
      st = connection.prepareStatement("select * from ? where ? = ?"); 
      st.setString(1, nomTable); 
      st.setString(2, nomcle); 
      st.setString(3, id); 
      rs = st.executeQuery(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return rs ; 
    } 

答えて

0

この問題を処理する方法は複数あります。ここに結果を表示するだけで素早く汚れたものがあります。 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> 


これを行うもう1つの(もっとクリーンな)方法は、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; 
} 
をそして、あなたがモデルにこれらのBeanを追加し、上記のように繰り返すことができます。 Springから RowMapperを迅速に実装するための BeanPropertyRowMapperもあります。

ResultSetでこのルートに進むのではなく、JPAの実装では、Listのオブジェクトを返す方がよい場合があります。それはいくつかの依存関係ですが、最終的には維持するコードが少なくなっています。

関連する問題