简体   繁体   English

JPA @ManyToMany 关系

[英]JPA @ManyToMany relationship

I have a case with Many to Many relationship我有一个多对多关系的案例

Following is the Book class with isbn as unique identifier以下是书 class 以isbn作为唯一标识符

 @Entity @Table(name = "book") public class Book implements Serializable { private static final long serialVersionUID = -4643154384069203197L; @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "isbn") private String isbn; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "book_author", joinColumns = { @JoinColumn(name = "bookId", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "authorId", referencedColumnName = "id") }) private Set<Author> authors = new HashSet<>(); // Getters and setters // hashcode and equals using only isbn

Following is the Author class with email as unique identifier以下是作者 class 与email作为唯一标识符

 @Entity @Table(name = "author") public class Author implements Serializable{ private static final long serialVersionUID = -6907306347041383886L; @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "email") private String email; @Column(name = "book") @ManyToMany(mappedBy = "authors") private Set<Book> books = new HashSet<>(); //getters and setters // hashcode and equals using only "email"

I am able to achieve unique Book, as the Set checks the isbn and removes all the duplicates.我能够获得唯一的书,因为 Set 检查isbn并删除所有重复项。 Since every Book can have many authors and vice versa I tried with Many to Many rekationship.由于每本书都可以有很多作者,反之亦然,我尝试了多对多 rekationship。

The problem comes with the unique email , Every book has an individual authors Set.唯一的问题是email ,每本书都有一个单独的作者集。 How can I achevie author with unique email in the author table?如何在作者表中获得具有唯一 email 的作者?

Help would be appreciated.帮助将不胜感激。 Thanks in Advance提前致谢

Change you @Column(name="email") into @Column(unique = true)将您的@Column(name="email")更改为@Column(unique = true)

name="email" is redundant since by default it will grab the name of the attribute which is anyways email name="email"是多余的,因为默认情况下它将获取属性的名称,无论如何都是 email

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

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