【发布时间】: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