views:

57

answers:

1

Hi folks,

I am facing some strange issue, I have a user table(use class) and a country table(country class). An user may have N number of countries. Hence, I have added a List of countries in the user class with the getter and setter method. In the table I have made the country_id as foreign key in user table. And, I have a @OneToMany on the user class.

Now when I try to persist the User class with a collection of countries in it, I see that the countries are never inserted :( I set two countries and insert an user. So I should be able to see 2 user rows with different countries. But I just see one.

I am just puzzled. Am I doing something wrong here?

Cheers, J

+2  A: 

I think you have mixed all things up

1) Each user may have 0..* countries, but is that "each countries can be owned by 1 user only"? I don't seems rational to me. Therefore I think it should be a @ManyToMany relationship instead of @OneToMany

2) "In the table I have made the country_id as foreign key in user table". For @OneToMany, the FK is not stored in the user table. It is simple to understand: each record of user can have 1 country_id, how can it represent the "ToMany" relationship? Storing the FK in the table is the default behaviour for @ManyToOne instead

3) "I see that the countries are never inserted". Automatically inserting countries when user is inserted, that's something to do with the cascade setting. Just add suitable cascade setting and it should work fine. (Though it don't sounds very rational for me)

The suggested way to do is: 1) Have User.countries being @ManyToMany 2) having a user_country table, with 2 FK, which are user_id and country_id, to store the relationship between users and countries

Adrian Shum

related questions