I'm exploring hibernate. I've ran into an issue I can overcome, however I would like to fix it with using cascade and see that hibernate can handle this. The most important factor is learning something new. Thank you in advance.
Before I explain my case, I want to give you the following information: The POJO mapping files are generated, so are the databags, so is the configuration file and the reverse engineering file. This is all set correct. The relation on both sides are many-to-many. I just need to insert or tweak one or two parameters in the mapping XML file: cascade or inverse.
Assume I have 3 tables: 'User', 'ItemsPerUser' and 'Item'. An user has a a PK username and a item has a PK name. The table ItemsPerUser has 2 FKS whom are a combined PK (username and itemname).
What I want to achieve is: I make up an user with one or more items, whom may exist (including the items whom may or may not exist). When I call an save() to the db trough the Hibernate SessionFactory,
I want hibernate to automatically insert the new user in the table User and new item(s) in the table Item and one or more according rows to the table ItemsPerUser. But I don't want to to overwrite rows in ItemsPerUser that don't belong to the user (because that happens now, if a new user has thesame item, it overwrites any row with that item and inserts the new name, meaning the old row is gone.) Now, if I don't set cascading I get an error: "Cannot add or update a child row: a foreign key constraint fails". If I set a cascade rule in the XML mapping file, the parent-child relation works correct for the two outer tables: User and Item, but not for the table ItemsPerUser. It seems it overwrites the rows with the new data.
Meaning the following:I make up a User object with multiple items. When I insert it, hibernate inserts a new user if it doesn't exist, it inserts new items when it doesn't exist, BUT it overwrites rows in the table ItemsPerUser. Meaning that for example I have an old row which is linked to an item and ANOTHER student, hibernate will overwrite that row with that item and change the partial key username to the new username.
Assume I start with an empty database and I insert a new user Roger, who has two items: coffee and water. This is an example what happens, and this is correct:
Code:
User ItemsPerUser Item
Roger Roger-coffee coffee
Roger-water water
Now when I insert a new user "Alfonzo" whom has the items coffee and soda, this happens:
Code:
User ItemsPerUser Item
Roger Alfonzo-coffee coffee
Alfonzo Roger-water water
Alfonzo-soda soda
See what happened there? The Roger-coffee row is gone :/Is it possible to solve this in the mapping files with an specific cascade combination or some other thing? Enlighten me!