jpa很多很多unique = true,如何保存

时间:2018-06-03 13:25:01

标签: java spring jpa

我有三张桌子

article(id, title, content)
article_tag(article_id, tag_id)
tag(id, name) // name(unique=true)

Article.java

@Data
@Entity
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false, unique = true, columnDefinition = "text")
    private String content;

    @JsonIgnore
    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(name = "article_tag",
            joinColumns = @JoinColumn(name= "article_id"),
            inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private Set<Tag> tags = new HashSet<>();

    private Timestamp createdAt;

    private Timestamp updatedAt;
}

Tag.java

@Data
@Entity
public class Tag {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String name;

    @JsonIgnore
    @ManyToMany(cascade = CascadeType.PERSIST, mappedBy = "tags")
    private Set<Article> articles = new HashSet<>();
}

我知道如何插入文章,但如何插入重复的标签?

表格标签已经有了(&#34; a&#34;,&#34; b&#34;,&#34; c&#34;)

enter image description here

我想插入带有标签&#34; a&#34;的文章,怎么办?

1 个答案:

答案 0 :(得分:0)

最后,我按<!DOCTYPE html> <html lang="en"> <head> <title>Loading...</title> <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta charset="utf-8"> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,600,700" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="/client.bundle.css"> </head> <body> <div id="app"></div> <script src="/bundle.js"></script> </script> </body> </html> @EqualsAndHashCode(exclude = {"tags"})完成。

Stackoverflow错误已经完成。

另外,我使用@ToString(exclude = {"tags"})来解决如何保存唯一列的问题。