本文介绍了如何在数据库中插入复合组件(菜单菜单)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现Composite Design模式,我需要在数据库中插入一个菜单,但是该菜单可能包含其他菜单和菜单项,因此当我尝试以递归方式插入它们时,出现错误,因为子菜单和子项需要知道尚未创建的父ID.

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

推荐答案

menu.getParent_id()对于最上面的Menu始终返回null,因为暗示它没有父级.由于菜单遍历从最顶部的Menu开始,因此您需要处理这种特殊情况.

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.

首先,您需要一种表示Menu的方法,该Menu在数据库表中没有父级.例如,您可以选择NULL来代表这一点.然后处理此案:

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

在递归调用该方法之前,您还需要在数据库中创建菜单.否则,menu.getParent_id()将为每个 Menu返回null,而不仅仅是最顶层的返回.因此,这需要在创建子菜单之前发生:int res = statement.executeUpdate();

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

这篇关于如何在数据库中插入复合组件(菜单菜单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 13:40