[英]How to link my primary key to to another table as a foreign key?
I am making a small project with a DB of a "book_store".我正在制作一个带有“book_store”数据库的小项目。 I am planning to have a two tables :
我打算有两个表:
Books -> table(It consists of id
as a Primary Key, and genre_id
as a Foreign_key of genre). Books -> table(它由
id
作为主键, genre_id
作为流派的 Foreign_key 组成)。 Genre table will have multiple genres(comedy, horror with its unique id) Genre -> table(id as a Primary Key, and yes this column will link to Books
table as a primary Key) Here is the implementation of Book table
流派表将有多种流派(喜剧,具有唯一 id 的恐怖片)流派 -> 表(id 作为主键,是的,此列将链接到
Books
表作为主键)这是Book table
的实现
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String author;
@JoinColumn(name = "genre_id", unique = true)
@OneToOne(cascade = CascadeType.ALL)
private Genre genre;
And here is my Genres
table这是我的
Genres
表
@Entity
@Table(name = "genres")
public class Genre {
@Id
@Column(name = "genre_id")
private int id;
private String genre;
So result of Book
table i am getting is like this: I am using PostgresQL所以我得到的
Book
表的结果是这样的:我正在使用 PostgresQL
and table of Genre
Genre和
Genre
表
enter image description here在此处输入图像描述
So my question is like this , while i am adding a new book ,and putting a genre 2 -> that means comedy, the Error is occured , that is telling that repeating of Unique key genres_pkey
?所以我的问题是这样的,当我添加一本新书并放入类型 2 -> 这意味着喜剧时,发生了
Error is occured , that is telling that repeating of Unique key genres_pkey
? Thanks for feedback!感谢您的反馈!
One to one means that a Book has a single genre and that a single genre can only be used for a book.一对一意味着一本书只有一个流派,一个流派只能用于一本书。 You have also specified
unique=true
, meaning that in the column genre_id
you cannot have the same id twice.您还指定了
unique=true
,这意味着在列genre_id
您不能有两次相同的 id。
Your description is not clear but I'm assuming multiple books can have the same genre.您的描述不清楚,但我假设多本书可以具有相同的类型。
The mapping in this case changes to a many-to-one:这种情况下的映射变为多对一:
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String author;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "genre_id")
private Genre genre;
}
It also seems weird there books cannot have multiple genres (what about horror comedy stories?).书不能有多种类型似乎也很奇怪(恐怖喜剧故事呢?)。 In that case you will need a bidirectional one-to-many .
在这种情况下,您将需要一个双向的一对多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.