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;
}