问题
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 recursively, I got an error because the submenu and sub items need to know the parent ID which isn't created yet.
public boolean insertMenu(Menu menu) {
try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO `menu` VALUES (NULL, ?, ?, ?)");
statement.setString(1, menu.getName());
statement.setDate(2, java.sql.Date.valueOf(menu.getLocalDate(menu.getDate())));
statement.setInt(3, menu.getParent_id()); // problem that this value always is null because it isn't created yet
for (MenuList child : menu.getChildren()) {
int x = child.getType();
if (x == 0) {
insertMenu((Menu) child);
} else {
MySqlMenuItemDAO a = new MySqlMenuItemDAO();
a.insertMenuItem((MenuItem) child);
}
}
int res = statement.executeUpdate();
if (res == 1) {
System.out.println("menu "+menu.getName()+" inserted");
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
回答1:
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();
来源:https://stackoverflow.com/questions/53892501/how-can-i-insert-a-composite-component-menu-of-menus-in-my-database