Vaadin Web应用开发教程(50): SQLContainer-使用FreeformQuery

jerry VaadinWeb 2015年11月25日 收藏

在大部分情况下使用TableQuery就可以满足应用要求,如果需要使用复杂查询,比如多表查询,则可以使用FreeformQuery。 缺省情况下FreeformQuery为只读,如果需要支持写操作,可以自行实现FreeformQueryDelegate接口。

  1. // Read-only queries
  2. public StatementHelper getCountStatement()
  3. public StatementHelper getQueryStatement(int offset, int limit)
  4. public StatementHelper getContainsRowQueryStatement(Object... keys)
  5.  
  6. // Filtering and sorting
  7. public void setFilters(List<Filter> filters)
  8. public void setFilters(List<Filter> filters,
  9. FilteringMode filteringMode)
  10. public void setOrderBy(List<OrderBy> orderBys)
  11. // Write support
  12. public int storeRow(Connection conn, RowItem row)
  13. public boolean removeRow(Connection conn, RowItem row)

使用多表查询,查询语句如下:

  1. SELECT C.FIRSTNAME , C.LASTNAME , INV.ID,INV.TOTAL
  2. FROM CUSTOMER C
  3. INNER JOIN INVOICE INV
  4. ON C.ID=INV.CUSTOMERID;
  1. void openTable(VerticalLayout layout){
  2. try {
  3. JDBCConnectionPool pool = new SimpleJDBCConnectionPool(
  4. "org.hsqldb.jdbc.JDBCDriver",
  5. "jdbc:hsqldb:file:/hsqldb/data/sample", "SA", "", 2, 5);
  6. FreeformQuery query = new FreeformQuery(
  7. "SELECT C.FIRSTNAME , " +
  8. "C.LASTNAME , INV.ID,INV.TOTAL " +
  9. "FROM CUSTOMER C " +
  10. "INNER JOIN INVOICE INV " +
  11. "ON C.ID=INV.CUSTOMERID;", pool, "ID");
  12. SQLContainer container = new SQLContainer(query);
  13. Table table = new Table("All Invoices", container);
  14. table.setSelectable(true);
  15.  
  16. layout.addComponent(table);
  17. } catch (SQLException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. }
  21. }

到目前为止,基本介绍完SQLContainer的用法,不过整体来说SQLContainer虽然使用简单方便,当功能有限,对应复杂的数据库应用还是可以直接使用JDBC和JPA等。