在Java中更新ManyToMany jointable

时间:2013-04-06 03:23:04

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

我使用netbeans生成了实体和外观。以下是工作/更新的示例:

我有2个表,它们通过连接表连接起作用:

用户

PK:userID

分类

PK:categoryID

User_Category

复合PK:userID |的categoryID (没有其他专栏)

更新联接表的方法,负责双方的关系:

    //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

技能

skillID

UserSkill

userID | skillID |年

重要的是:用户拥有用户ID。技能具有技能ID,UserSkill具有由userID和skillID以及另一列组成的复合主键;年。

2 个答案:

答案 0 :(得分:0)

如果您使用的是hibernate,只需在类Cascade.UPDATE的{​​{1}}属性上添加UserSkill即可解决该问题。

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

如果您在执行此操作时遇到任何具体问题,请告知我更新我的回答

答案 1 :(得分:0)

如果没有看到你的实体课程,很难确定,但你可能正在寻找类似的东西:

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

CascadeType