• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

many-to-many mapping, how NOT to insert into child

 
Ben Gateau Jr
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am new to Hibernate, as will soon be obvious

I have a many-to-many relationship between Clients and Products. Client contains Set of Products.

Client.java

Product.java

Client.hbm.xml

Product.hbm.xml


This setup is working fine when I create bunch of Products, add them to the Client's Set and save the Client. Records are inserted in CLIENT, PRODUCT, and link table CLIENT_PRODUCT. But now I already have some products in the PRODUCT table, and I want to add new Clients to the system and assign the existing Products to them. In this current setup Hibernate is trying to insert Products into PRODUCT table and I'm getting an Exception. My question is, how to configure the system to inserts Clients when new and to insert new rows in the link table, but not to try to insert Products if they already exist? I tried different 'cascade' values(none, save-update) and I tried to set 'inverse' on a set, but no luck.

Thanks, Ben
 
Sridhar Santhanakrishnan
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you using save() or saveOrUpdate()?
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you creating the products yourself or obatining it from the DB and setting them unchanged in the new client?
 
Ben Gateau Jr
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sridhar,
Initially I had save(), but I've changed it since to have saveOrUpdate(). I guess 'OrUpdate' part is only working on the Client table.

Bauke,
I am getting Product objects from the DB and setting them unchanged in the new Client. What I would like is to have inserts only in CLIENT and CLIENT_PRODUCT tables. At the moment I can either have attempt at an insert to all 3 tables (using cascade=all) or only to the CLIENT table (using cascade=none).

Thanks, Ben.
 
Ben Gateau Jr
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My apologies - there was an error in my code. I was getting Products from the DB, but when they were selected from the listbox, I was only setting the name for each before adding them to the Set, and I wasn't setting the ID fields. What can I say ops:
Cheers, Ben.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic