【问题标题】:Updating ManyToMany jointable in Java在 Java 中更新可连接的多对多
【发布时间】:2013-04-06 03:23:04
【问题描述】:

我使用 netbeans 生成实体和外观。以下是一个有效/更新的示例:

我有 2 个表,它们通过它工作的连接表连接:

用户

PK:用户ID

类别

PK:类别ID

用户类别

复合 PK:用户 ID |类别ID (没有其他列)

更新连接表的方法,照顾双方的关系:

    //set up user Categories
    List<Category> categoryList = new ArrayList<Category>();

    //get all the current categories for the current user
    categoryList.addAll(user.getCategoryList());

    //clear out user for that type (to reset)
    for(Category c : categoryList){
        tempUserList.clear();
        tempUserList = c.getUserList();
        tempUserList.remove(user);
        c.setUserList(tempUserList);
        categoryFacade.edit(c);
    }

    categoryList.clear();
    //where selectedCategoryListString is a list of category names
    for(String s : selectedCategoryListString){
        categoryList.add(categoryFacade.findByCategoryName(s));
    }

    for(Category c : categoryList){
        tempUserList.clear();
        tempUserList = c.getUserList();
        tempUserList.add(user);
        c.setUserList(tempUserList);
        categoryFacade.edit(c);
    }
    user.setCategoryList(categoryList);
    userFacade.edit(user);

上述工作,它照顾双方的关系。我被困的地方在下面。由于额外的“年”列,“技能”没有方法“.getUserList()”。相反,它有一个“.getUserSkillList()”。我不知道应该如何像上面那样更新连接表。我们可以假设“年”列每次都设置为“”(空白)。

下面:有问题的表/关系:

用户

用户ID

技能

技能ID

用户技能

用户ID |技能ID |年

重要的是:用户有一个用户 ID。 Skill有一个skillID,UserSkill有一个由userID和skillID和另一列组成的复合主键;年。

【问题讨论】:

  • 你在使用休眠,对吧?
  • 对不起,我应该指定:EclipseLink

标签: java jpa many-to-many relationship entities


【解决方案1】:

如果您使用的是休眠,只需在 User 类的 UserSkill 属性上添加 Cascade.UPDATE 即可解决该问题。

但是,由于您没有使用休眠,您可以手动完成。更新 User 时,检索与它相关的 UserSkills 并更新它们。

如果您对此有任何具体问题,请告诉我以更新我的答案

【讨论】:

    【解决方案2】:

    如果不查看您的实体类很难确定,但您可能正在寻找类似的东西:

    @ManyToMany(cascade = CascadeType.MERGE, ...)
    

    CascadeType

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2015-08-06
      • 1970-01-01
      • 2013-04-24
      相关资源
      最近更新 更多