代码之家  ›  专栏  ›  技术社区  ›  Royce

只将行删除到联接表中

  •  0
  • Royce  · 技术社区  · 6 年前

    是否可以将行删除到由@manytomy注释创建的联接表中?

    使用此架构:

    public Set<Tag> tags (列表 ARTICLE 类)对应的行 TAGS_ARTICLES 也被删除了,但没有标记到 TAG 表。

    代码

    article.getTags().remove(tag);

    这一行从列表中删除标记,但是数据库中没有完成更改。

    结论

    How to delete a row in join table with JPA ,但相对标记也必须删除(不是我的情况)。

    谢谢。

    编辑1:数据库中的预期结果

    ARTICLE
    
    | article_id |
    | a1         |
    | a2         |
    | a3         |
    
    TAGS_ARTICLES
    
    | article_id | tag_id |
    | a1         | t1     |
    | a1         | t2     |
    | a2         | t2     |
    
    TAG
    
    | article_id |
    | t1         |
    | t2         |
    

    从a1标签列表中删除t1后

    ARTICLE
    
    | article_id |
    | a1         |
    | a2         |
    | a3         |
    
    TAGS_ARTICLES
    
    | article_id | tag_id |
    | a2         | t1     |
    | a2         | t2     |
    
    TAG
    
    | article_id |
    | t1         |
    | t2         |
    

    @Entity
    public class Article {
         ...
         @ManyToMany
         @JoinTable(name = "tags_articles",
            joinColumns = @JoinColumn(name = "idarticle"),
            inverseJoinColumns = @JoinColumn(name = "idtag")
         )
         private Set<Tag> tags = new HashSet<>();
         ...
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   LppEdd    6 年前

    编辑:参见注释

    使用此设置应产生所需的结果

    class Article {
       ...  
    
       @ManyToMany
       @JoinTable(...)
       private Set<Tag> tags = new HashSet<>();
    }
    
    class Tag {
       ...
    
       @ManyToMany(mappedBy = "tags")
       private Set<Article> articles = new HashSet<>();
    }
    

    这个 Article


    旧答案

    从中删除标记时 public Set<Tag> tags 类)也删除了TAGS_ARTICLES中相应的行,但是

    我明白了 孤儿 不会删除记录。你想删除它们。这是对的吗?

    @Cascade 注释( documentation ).
    只是给你的 Collection<T> 字段。

    @ManyToMany(...)
    @Cascade(CascadeType.REMOVE) // or CascadeType.DELETE
    private Set<Tag> tags = new HashSet<>();
    

    org.hibernate.annotations

        2
  •  1
  •   Sai prateek    6 年前

    实体操作的行为取决于关系的所有权,这取决于您将 地图佩比 mappedBy 是不是所有者的那个。关系的双方不能是所有者。

    在这里你需要决定正确的主人。假设标签是所有者。然后,删除标记时,关系标记\u项目将自动更新。删除标记项目时,您必须自己删除关系。

    @Entity
    public class Tag{
        @ManyToMany
        Set<Tag_Articles> articles;
        //...
    }
    
    @Entity
    public class Tag_Articles{
        @ManyToMany(mappedBy="articles")
        Set<Tag> tags;
        //...
    }
    

    对于上面这样的实体关系,您可以尝试这样的方法-

    entityManager.remove(articles)
    for (Tag tag: articles.tags) {
         tag.articiles.remove(articles);
    }