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
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();