如何将 BeanItemContainer 绑定到 Combobox

How to bind BeanItemContainer to Combobox

我有 BeanItemContainer,我通过 jdbc 从数据库加载它:

BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, mybeanDao.findAll());

这就是我将其附加到组合框的方式:

Combobox combo = new Combobox();
combobox.setContainerDataSource(myBeans);

到目前为止,还不错。我收到了我想要的东西,但现在我有一个问题 - 我如何获得已选择的实际 ID?这必须同步(在组合框中选择的 ID 是数据库中的实际条目)。

我不知道如何解决这个问题

请帮忙

P.S MyBean class

public class MyBean {

    private Long id;
    private String field1;

*** getters /setters ***
  and toString() {} method 
}

如果我对问题的理解正确 combo.getValue() 应该会为您提供与当前选择相关的 MyBean 实例(如果未选择任何项目,则为 null)

这是代码:

@Theme("mytheme")
public class MyUI extends UI {

@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSpacing(true);
    setContent(layout);

    BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, getBeans());

    ComboBox combo = new ComboBox();
    combo.setContainerDataSource(myBeans);
    combo.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
    combo.setItemCaptionPropertyId("field");

    combo.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent event) {
            MyBean bean = (MyBean) combo.getValue();

            Notification notif = new Notification("Selected Bean Id: "+bean.getId(), Notification.Type.TRAY_NOTIFICATION);
            notif.setPosition(Position.TOP_CENTER);
            notif.show(Page.getCurrent());
        }
    });

    layout.addComponent(combo);
}

@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}

public class MyBean {

    private Long id;
    private String field;

    public MyBean(Long id, String field) {
        this.id = id;
        this.field = field;
    }

    public Long getId() {
        return id;
    }

    public String getField() {
        return field;
    }

}

public ArrayList<MyBean> getBeans() {
    ArrayList<MyBean> beans = new ArrayList<>();

    MyBean bean = new MyBean(1l, "Vikrant");
    beans.add(bean);

    bean = new MyBean(2l, "Rampal");
    beans.add(bean);

    bean = new MyBean(3l, "viky");
    beans.add(bean);


    return beans;
}

}