Search code examples
javaspringforeign-keys

BASIC SPRING: Foreign Keys and Relational Tables


I'm creating a simple Java-Spring project using MySQL server. While creating tables on the database I see that Spring creates some sort of "relational tables".

OneToMany, ManyToOne tables

But all of them are empty.

I check the table "ticket" and the column gig_id (Foreign key) is filled with the right value.

Foreign Keys

The system works.

Should I have both the tables filled, or leave it as Spring creates them?


Solution

  • In my experience It's better to have relationship on only one side

    To ensure that only one relational table is created and to prevent Spring Boot from creating another table automatically, it's recommended to use only one side of the mapping for the relationship.

    To accomplish this, you can use the mappedBy attribute on the non-owning side of the relationship mapping. For example, if you want to ignore the creation of the intermediate table for a @OneToMany relationship, you can add the mappedBy attribute to the @ManyToOne side of the relationship and specify the column name to map to: