Home > OS >  How to link my primary key to to another table as a foreign key?
How to link my primary key to to another table as a foreign key?

Time:06-18

I am making a small project with a DB of a "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). 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

@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

@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

and table of 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? Thanks for feedback!

CodePudding user response:

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.

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.

  • Related