Vaadin Web应用开发教程(49): SQLContainer-引用其它SQLContainer

jerry VaadinWeb 2015年11月25日 收藏

数据库表之间存在参考关键,这对应到数据库通常为外键引用。Vaadin 的SQLContainer提供了不同SQLContainer之间引用的有限支持,但其实现主要是通过Java 代码来实现的,并不需要数据库的表之间一定要有外键定义。
给一个SQLContainer添加引用的方法为:

  1. public void addReference(SQLContainer refdCont,
  2. String refingCol, String refdCol);

refdCont为被引用的SQLContainer,refingCol 为源SQLContainer对应的列名,refdCol为目标SQLContainer被参照的列名。
要注意的是SQLContainer不支持同一个SQLContainer参照自身。

还是以Customer ,Invoice 为例。 显示所有Invoice,但点击某个Invoice,显示对应的Customer的姓名。

  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. TableQuery customers = new TableQuery("CUSTOMER", pool);
  7. customers.setVersionColumn("OPTLOCK");
  8. TableQuery invoices = new TableQuery("INVOICE", pool);
  9. customers.setVersionColumn("OPTLOCK");
  10. final SQLContainer customerContainer
  11. = new SQLContainer(customers);
  12. final SQLContainer invoiceContainer
  13. = new SQLContainer(invoices);
  14. Table table = new Table("All Invoices", invoiceContainer);
  15. table.setSelectable(true);
  16.  
  17. // Send changes in selection immediately to server.
  18. table.setImmediate(true);
  19.  
  20. invoiceContainer.addReference(customerContainer,
  21. "CUSTOMERID", "ID");
  22. table.addListener(new ItemClickListener(){
  23.  
  24. public void itemClick(ItemClickEvent event) {
  25. RowItem rowItem=(RowItem)event.getItem();
  26. RowItem customerItem
  27. =(RowItem)invoiceContainer
  28. .getReferencedItem(rowItem.getId(),
  29. customerContainer);
  30. customerLabel.setValue(customerItem
  31. .getItemProperty("FIRSTNAME")
  32. .toString()
  33. +" "+ customerItem
  34. .getItemProperty("LASTNAME")
  35. .toString());
  36. }});
  37. layout.addComponent(table);
  38. } catch (SQLException e) {
  39. // TODO Auto-generated catch block
  40. e.printStackTrace();
  41. }
  42. }

SQLContainer和参照其它SQLContainer的主要方法如下:

  1. public boolean setReferencedItem(Object itemId,
  2. Object refdItemId, SQLContainer refdCont)
  3. public Object getReferencedItemId(Object itemId,
  4. SQLContainer refdCont)
  5. public Item getReferencedItem(Object itemId,
  6. SQLContainer refdCont)
  7. public boolean removeReference(SQLContainer refdCont)

这里不再一一说明了。