当我将组件添加到 Vaadin 的组件(例如TabSheet
or Tree
)时,添加的组件会被缓存。当用户单击选项卡(或树节点)时,如果它包含 db data ,则显示 stale data ,不反映最新的 db 状态。
我想知道是否有任何方法可以确保加载最新数据?
我通过定义我的自定义界面来解决这个问题:
public interface Reloadable {
void reload();
}
并且每个组件都实现了这个 Reloadable 接口,例如:
@SpringComponent
public class TeachersView extends VerticalLayout implements Reloadable, Serializable {
@Inject
private TeacherDao teacherDao;
private final static int PAGESIZE = 10;
private MTable<Teacher> mTable = new MTable<>(Teacher.class);
@PostConstruct
public void init() {
// mTable settings skip here
reload();
addComponent(mTable);
}
@Override
public void reload() {
mTable.setBeans(new SortableLazyList<>(
sortablePagingProvider ,
() -> (int) teacherDao.count() ,
PAGESIZE
));
}
private SortableLazyList.SortablePagingProvider<Teacher> sortablePagingProvider =
(firstRow, asc, sortProperty) -> {
return teacherDao.findAll(
new PageRequest(
firstRow / PAGESIZE, PAGESIZE,
asc ? Sort.Direction.ASC : Sort.Direction.DESC,
sortProperty == null ? "id" : sortProperty
)
).getContent();
};
}
这个视图被注入到UI
类中:
@SpringUI(path = "/ui")
@Theme("valo")
public class VaadinUI extends UI {
@Inject
private TeacherDao teacherDao;
@Inject
private TeachersView teachersView;
@Override
protected void init(VaadinRequest vaadinRequest) {
Panel panel = new Panel("Admin Panel");
HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
splitPanel.setSplitPosition(15, Unit.PERCENTAGE);
panel.setContent(splitPanel);
Tree tree = new Tree("Menu");
splitPanel.setFirstComponent(tree);
Label home = new Label("Home");
Map<String, Component> map = new HashMap<>();
map.put("Teachers", teachersView);
map.put("Home", home);
map.forEach((k, v) -> tree.addItem(k));
tree.addItemClickListener(event -> {
Component view = map.get(event.getItemId());
if (view instanceof Reloadable) {
((Reloadable) view).reload();
}
splitPanel.setSecondComponent(view);
});
splitPanel.setSecondComponent(home);
setContent(panel);
} // init()
}
注意tree.addItemClickListener
,我必须检查每个组件是否实现Reloadable
,如果为 true,则调用它。
有用 。但我不知道这是否是实现这一目标的标准方式?我认为这应该是一个常见的场景,应该有类似组件的内置接口来实现,比如onRender
那个(但我找不到)。我错过了什么吗?
谢谢。