Hi all,
First post on coderanch for me! I am very new (say about 8hrs) to Hibernate so I am hoping I can explain this properly.
I have a situation where I need to record the countries a user has logged in from. This information is read in from an xml file and persisted to the database. It is possible that users can have a history of logging in from many countries if they travel. When I read in the country for each user I only have the name of the country and not the primary key that the country is associated with in the DB. So I am currently creating a Country object, setting the name (without and id) and then adding that object to the countries list in the User object.
To implement this I have 3 tables, User, Country (purely a reference table) and User_Country (to handle the many-to-many situation). In my User @Entity class I am using the @JoinTable on my getCountries() method to tell hibernate about the many-to-many relationship. When I persist the User object it it is successfully persisting the User and User_Country entries but it is also creating new duplicate entries in the Country table and using these entries as the country_id in the User_Countries table. I could mark the countryName field as unique in the @Column but I suspect that won't fix my problem as it will attempt to insert a duplicate and fail.
I have 3 thoughts as to why this is happening:
1. Because I am adding countries to the User without and ID, hibernate thinks these are new countries and adding them to the database before finally updating the User_Countries table. Should I be looking up the Country by the country name and adding the complete object to the User class (can you look up record in Hibernate purely based on a unique field??)
2. I have done something wrong with the @JoinTable and I am missing something that tells Hibernate not to update the Countries table and to only update the User and User_Countries table
3. I am way off and it's another problem all together
Is anyone able to help out? Hopefully that makes sense. Thanks in advance!!
My cut down User class and Country class Code is below.
User.java
Country.java