![](/img/trans.png)
[英]How can I make User ID primary key link to user_id in another table as a foreign key?
[英]How to link my primary key to to another table as a foreign key?
我正在制作一个带有“book_store”数据库的小项目。 我打算有两个表:
Books -> table(它由id
作为主键, genre_id
作为流派的 Foreign_key 组成)。 流派表将有多种流派(喜剧,具有唯一 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;
这是我的Genres
表
@Entity
@Table(name = "genres")
public class Genre {
@Id
@Column(name = "genre_id")
private int id;
private String genre;
所以我得到的Book
表的结果是这样的:我正在使用 PostgresQL
和Genre
表
所以我的问题是这样的,当我添加一本新书并放入类型 2 -> 这意味着喜剧时,发生了Error is occured , that is telling that repeating of Unique key genres_pkey
? 感谢您的反馈!
一对一意味着一本书只有一个流派,一个流派只能用于一本书。 您还指定了unique=true
,这意味着在列genre_id
您不能有两次相同的 id。
您的描述不清楚,但我假设多本书可以具有相同的类型。
这种情况下的映射变为多对一:
@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;
}
书不能有多种类型似乎也很奇怪(恐怖喜剧故事呢?)。 在这种情况下,您将需要一个双向的一对多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.