简体   繁体   English

如何使用JPA删除连接表中的一行

[英]How to delete a row in join table with JPA

I have the model below : an article can have some tags and a tag can be on some articles.我有下面的模型:一篇文章可以有一些标签,一些文章可以有一个标签。 So it is a many-to-many relationship with 3 tables :所以它是一个多对多的关系,有 3 个表:

  • ARTICLE文章
  • ARTICLE_TAG ARTICLE_TAG
  • TAG标签

When I delete a tag, I want to delete :当我删除标签时,我想删除:

  • the tag in TAG标签中的标签
  • all relations between the tag and the articles tagged in ARTICLE_TAG标签与 ARTICLE_TAG 中标记的文章之间的所有关系

But I don't want to delete the articles in ARTICLE of course.但我当然不想删除ARTICLE中的文章。

How can I do that ?我怎样才能做到这一点 ?

I try this, but it doesn't work :我试试这个,但它不起作用:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
for (Article article : tagToDelete.getArticles()) {
    article.getTags().remove(tagToDelete);
}
session.delete(tagToDelete);

Thanks !谢谢 !

@Entity
@Table(name="ARTICLE")
public class Article extends AbstractAuditedEntity {

    @Id
    @Column(name="ID", nullable=false)
    private Long id;

    @ManyToMany
    @JoinTable(name="ARTICLE_TAG", joinColumns=@JoinColumn(name = "ARTICLE_ID"), inverseJoinColumns=@JoinColumn(name = "TAG_ID"))
    private Set<Tag> tags = new HashSet<>();

    public Article() {}

    /** Getters & Setters */
}

@Entity
@Table(name="TAG")
public class Tag {

    @Id
    @Column(name="ID", nullable=false)
    private Long id;    

    @ManyToMany(mappedBy="tags")
    private Set<Article> articles = new HashSet<>();

    public Tag() {}

    /** Getters & Setters */        
}

Found the solution.找到了解决办法。 On delete, we need to make sure not to cascade the delete to the Article, and vice-versa.在删除时,我们需要确保不要将删除级联到文章,反之亦然。

@ManyToMany(cascade={PERSIST, DETACH})
@JoinTable(name="ARTICLE_TAG",
           joinColumns=@JoinColumn(name = "ARTICLE_ID"), 
           inverseJoinColumns=@JoinColumn(name = "TAG_ID"))
private Set<Tag> tags = new HashSet<>();

My problem was using CascadeType.All , which by default includes CascadeType.REMOVE , which will cascade the deletion of an article to the Tags it contains.我的问题是使用CascadeType.All ,默认情况下包括CascadeType.REMOVE ,它将把文章的删除级联到它包含的标签。

You can also add cascade={PERSIST, DETACH} to your Tag entity to prevent the deletion of a Tag to delete its associated Article.您还可以将cascade={PERSIST, DETACH}到您的标签实体,以防止删除标签以删除其关联的文章。

I try to delete the records like that.我尝试删除这样的记录。 It worked.有效。

Pass id to API and then it deletes that each record.id传递给 API,然后它会删除每条记录。 Try it.尝试一下。

Have any issues please let me know.有任何问题请告诉我。

@Entity
@Table(name="ARTICLE") 
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "article_id")
    private int id;

    @ManyToMany(mappedBy="article")
    private Set<Article_Tag> article_tag = new HashSet<>();

    public Article() {}

    /** Getters & Setters */



@Entity
@Table(name="TAG")
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "tag_id")
    private int id;

    @ManyToMany(mappedBy="tag")
    private Set<Article_Tag> article_tag = new HashSet<>();

    public Tag() {}

    /** Getters & Setters */



@Entity
@Table(name="ARTICLE_TAG")
public class Article_Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.DETACH})
    @joinColumn(name = "article_id")
    private Set<Article> articles = new HashSet<>();

    @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.DETACH})
    @joinColumn(name = "tag_id")
    private Set<Tag> tags = new HashSet<>();

    public Article_Tag() {}

    /** Getters & Setters */



public interface Article_TagRepository extends JpaRepository<Article_Tag, Integer>{

    Article_Tag findByArticle(Article id);

    Article_Tag findByTag(Tag id);

}



@RestController
@RequestMapping(value = "/")
public class Article_TagController {

@Autowired
private Article_TagRepository article_tagRepository;

@GetMapping("/delete/article/{id}")
public String DeleteArticleById(@PathVariable("id") Article id) {
    Article_Tag article_tag = article_tagRepository.findByArticle(id);
    Integer article_tag_id = article_tag.getId();
    article_tagRepository.deleteById(article_tag_id);
    return "Article Successfully Deleted !!!";
}

@GetMapping("/delete/tag/{id}")
public String DeleteTagById(@PathVariable("id") Tag id) {
    Article_Tag article_tag = article_tagRepository.findByTag(id);
    Integer article_tag_id = article_tag.getId();
    article_tagRepository.deleteById(article_tag_id);
    return "Tag Successfully Deleted !!!";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM