how can i insert a composite component (menu of menus) in my database

前端 未结 1 1642
失恋的感觉
失恋的感觉 2021-01-29 07:05

I am implementing the Composite Design pattern and I need to insert a menu in the database but the menu may consist of other menus and menu items so when I tried to insert them

相关标签:
1条回答
  • 2021-01-29 07:11

    menu.getParent_id() will always return null for the top-most Menu because by implication it doesn't have a parent. Since menu traversal begins with the top-most Menu you need to handle this specific case.

    Firstly, you need a way to represent a Menu without a parent in your database table. For example, you may choose NULL to represent this. Then handle the case:

    if(menu.getParent_id() == null) {    
        statement.setNull(3, java.sql.Types.INTEGER);
    else {
        statement.setInt(3, menu.getParent_id());
    }
    

    You also need to create the menu in the database before calling the method recursively. Otherwise menu.getParent_id() will return null for every Menu and not just the top-most. So this needs to happen before creating the submenus: int res = statement.executeUpdate();

    0 讨论(0)
提交回复
热议问题