【问题标题】:Hibernate - automatic @ManyToMany updateHibernate - 自动 @ManyToMany 更新
【发布时间】:2015-06-28 16:33:15
【问题描述】:

我有Article实体,它有相关的Tags:

@Entity
@Table(name = "articles")
public class Article implements Serializable{
   //other things

   @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
   private List<Tag> tags;
}

还有Tag实体,其中有相关的Articles:

@Entity
@Table(name = "tags")
public class Tag implements Serializable{
    //other things

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Article> articles;
}

有没有机会配置Annotations,如果我用指定的Tag保存Article

//simplified code
Tag tag = new Tag();
tags.add(tag)

article.setTags(tags);

articleService.save(article);

Tag相关的Articles 将自动更新,无需专门调用add方法(tag.getArticles().add(article))?还是我必须手动完成?

这是单元测试的一部分,它显示了我试图实现的目标:

service.save(new TagDTO(null, tagValue, emptyArticles));
TagDTO tag = service.getAll().get(0);
List<TagDTO> tags = new ArrayList<>();
tags.add(tag);
articleService.save(new ArticleDTO(null, tags, articleContent));

List<ArticleDTO> articles = articleService.getAll();
assertEquals(1, articles.size());
final ArticleDTO articleWithTags = articles.get(0);
assertEquals(1, articleWithTags.getTags().size());
tags = service.getAll();
assertEquals(1, tags.size());
final TagDTO tagWithArticle = tags.get(0);
final List<ArticleDTO> articlesWithTag = tagWithArticle.getArticles();
assertEquals(1, articlesWithTag.size()); //it fails

现在失败了,因为Tag 没有更新为相关的Article

提前感谢您的回答!

【问题讨论】:

    标签: java hibernate orm many-to-many cascade


    【解决方案1】:

    您在多对多关系中缺少 mappedBy 属性。如果你不使用它,那么hibernate认为你有两个不同的单向关系。 我的意思是你的代码代表了这一点:

    • Article * ------------------[tags]-&gt; * Tag
    • Tag * ------------------[articles]-&gt; * Article

    而不是这个:

    • Article * &lt;-[articles]------[tags]-&gt; * Tag

    这是在ArticleTag 之间建立一个多对多双向关系的一种方法。注意 Tag->articles 集合上的 mappedBy 属性。

    @Entity
    @Table(name = "articles")
    public class Article implements Serializable{
       //other things
    
       @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
       private List<Tag> tags;
    }
    
    @Entity
    @Table(name = "tags")
    public class Tag implements Serializable{
        //other things
    
        @ManyToMany(mappedBy="tags" ,cascade = {CascadeType.PERSIST, CascadeType.MERGE})
        private List<Article> articles;
    }
    

    编辑:查看Hibernate Documentation,了解如何编写不同的双向关联方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      相关资源
      最近更新 更多