Reputation: 17
I have classes -> Country and City.
My Country model class:
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Long id;
@NotEmpty(message = "Name of country is mandatory.")
@Column(unique = true)
private String nameOfCountry;
@NotBlank(message = "Name of capital is mandatory.")
private String capital;
@Max(value = 17098242L, message = "Maximum value for population = 10000000000")
private Long surface;
private String countryCode;
private String telephoneCode;
@OneToMany(cascade = CascadeType.PERSIST)
@JoinColumn(name = "country_Id", updatable = false, insertable = false)
private List<CityModelDao> cityModelDao;
My City model class:
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Long id;
@NotEmpty(message = "Name of country is mandatory.")
@NotNull
@Column(nullable = false, unique = true)
private String nameOfCity;
I know that I don't have here @ManyToOne, but I still do it wrong and now I haven't got more ideas.
My response from get countries:
And this is it what i want.
But when i call to get cities my response is:
Unfortunately I havent got information about country.
In db I have in cities information about fk from country:
Could you help me to do works relation? I ve tried something like:
CityModel:
@ManyToOne()
@JoinColumn(name = "country_Id")
private CountryModelDao countryId;
CountryModel:
@OneToMany(mappedBy = "countryId", orphanRemoval = true, cascade = CascadeType.PERSIST)
private List<CityModelDao> cityModelDao;
But it was wrong. And when I tried with above relation city, I got error.
Could You tell me how to do correct @ManyToOne in this case? What I do wrong?
Thanks
Upvotes: 0
Views: 2407
Reputation: 271
The most simplistic bi-directional OneToMany relationship model should be:
@OneToMany(mappedBy = "countryId")
private List<CityModelDao> cityModelDao;
You set Country as the owner of the relationship Country - City; You expect an attribute 'countryId' in the CityModelDao;
@ManyToOne
@JoinColumn(name = "country_id")
private CountryModelDao countryId;
You will populate with data based on a join operation that will be executed on the column country_id from the CityModelDao table.
Of course, afterwards, you can enrich the annotations with orphan removal, cascade type etc.
LE: You are using this via REST and you need to avoid the infinite loop.
Please update the relations to:
@JsonManagedReference
@OneToMany(mappedBy = "countryId")
private List<CityModelDao> cityModelDao;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "country_id")
private CountryModelDao countryId;
Upvotes: 2