Hibernate version: 3.1.3
Mapping documents for class Product :
<set name="types" table="PRODUCT_TYPES" >
<key column="PRODUCT_ID" />
<many-to-many class="Type" >
<column name="TYPE_ID"/>
</many-to-many>
</set>
Hi,
I tried to managed an association table with a "many-to-many set". The insert/update/delete operations don't work in all cases.
For example, if I try to do the following actions :
Code:
// begin transaction
Product prod = getSessionFactory().getCurrentSession().load(Product .class, 1);
prod.getTypes().clear();
// end transaction
SQL generated : delete from PRODUCT_TYPES where PRODUCT_ID=?
=> Hibernate delete all the rows in PRODUCT_TYPES table for the my current product with which is ok!
But if I try to clear and add an element, it doesn't work properly. For example :
Code:
// assuming myType has been loaded in the same session and prod.getTypes() is not empty.
// begin transaction
Product prod = getSessionFactory().getCurrentSession().load(Product .class, 1);
prod.getTypes().clear();
prod.getTypes().add(myType);
// end transaction
SQL generated :
delete from PRODUCT_TYPES where PRODUCT_ID=? and TYPE_ID=?
insert into PRODUCT_TYPES (PRODUCT_ID, TYPE_ID) values (?, ?)
=> Hibernate generate a delete/insert in PRODUCT_TYPES table for the type myType but does not delete the old association lines (that has been deleted by the clear method).
I should have the two sql statements :
delete from PRODUCT_TYPES where PRODUCT_ID=?
insert into PRODUCT_TYPES (PRODUCT_ID, TYPE_ID) values (?, ?)
I can understand that hibernate can't know if the set has been clear or not, so it doesn't generate a delete. I thought I could flush the session after calling clear method but it is not a very good practice I think.
Can I manage an association table only by using the set in my object or should I write some methods in my DAO to handle this case ?
Thanks,