Search code examples
hibernateone-to-manymany-to-onemappedby

ManyToOne and OneToMany


I use Hibernate and I have entities:

@Data
@Entity
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "country_nm")
    private String countryName;
}

@Data
@Entity
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "city_nm")
    private String cityName;
}

Country can have many cities, city has only one country. What is the best way to associate these entities?

1) add City city field in City class and add @ManyToOne and @JoinColumn anotations above it? As a result we will have two tables: country and city, city table will have country_id column.

2) add Country country field in Country class and @OneToMany(mappedBy='country')above it and add City city field in City class and add @ManyToOne anotations above it? In this case there will be three tables: country, city and combining table country_city


Solution

  • 1) add City city field in City class and add @ManyToOne and @JoinColumn anotations above it? As a result we will have two tables: country and city, city table will have country_id column.

    I suppose you mean add Country country field in City class, yes this would be right about it if you are aiming for unidirectional relations, but the joinColumn should not be in the owning entity, it should be in the none owning entity so you would have to go to the Country class and add a list of cities there and annotate them with @OneToMany with join column.

    2) add Country country field in Country class and @OneToMany(mappedBy='country')above it and add City city field in City class and add @ManyToOne anotations above it? In this case there will be three tables: country, city and combining table country_city

    there are many wrong things about this solution, first you cannot have "@oneToMany(mappedBy='country)" like this, you can use it only if you applied the first solution and you want to make the relation bidirectional and even though this will not generate a third class, if you want to generate a third class it you will need @JoinTable in your owning class instead of @JoinColumn