OK, so today I tried a basic Hibernate tutorial and I'm struggling to make it behave how I want.
This is a simple snippet, assume all other fields/methods are defined (e.g. id etc.)
@Entity
@Table(name = "CITIES")
public static class City {
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
private Country country;
}
@Entity
@Table(name = "COUNTRIES")
public static class Country {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<City> cities;
}
The above solution utilizes an (automatically created) association table - COUNTRY_CITIES
, but
this does work only in one way - i.e. I see country's cities (when I select one), but I don't see a city's country (when I select a city).
So what should I do to make cities see their country?
I can add a @JoinColumn(name = "COUNTRY_ID")
to the Country.cities
field and it works in two ways.
But I don't like to add columns to city's table from country's code.
So I added the @JoinColumn
to the City.country
field and it didn't work.
So - how to make the association work in 2 ways w/o an association table??
OK, to be precise: I used the above code add feed the DB with this objects:
Country germany = new Country("Germany", new HashSet<>(asList(
new City("Berlin"),
new City("Hamburg")
)));
.. and viewed the DB. It looked like this:
table COUNTRIES_CITIES (note, I didn't declare it; Hibernate does automatically)
COUNTRIES_ID CITIES_ID
1 1
1 2
table COUNTRIES
ID NAME
1 Germany
table CITIES (note I didn't declare the COUNTRY_ID column! Hibernate again..)
ID NAME COUNTRY_ID
1 Berlin null
2 Hamburg null
And that's it. Fetching the country gives me the cities, fetching the city gives me null country.
If I add a @JoinColumn
to the Country
class, then the a column is appended to the CITIES
table and fetching works two ways.