This question has been asked many times, but I did not find a clear solution, so I'm asking this again here in the hope someone can help.
The scenario is like this: I have a 'person' which can have zero, one or more 'products'.
So I made a one-to-many set association from Person to Product. The association is uni-directional, from Person to Product.
What I want is that when I delete a Person, the products are deleted as well.
I, however, want hibernate to do this
in one single query, like: 'delete from product where person_id = <id>'
But whatever I try, hibernate just keeps on deleting the products one by one:
Code:
31398 [main] DEBUG org.hibernate.SQL - delete from product where id=?
31399 [main] DEBUG org.hibernate.SQL - delete from product where id=?
31400 [main] DEBUG org.hibernate.SQL - delete from person where id=?
In this case a delete statement per product entry would yield in serious performance degradation
(This is only a proof of concept for a table who can contain thousands of childs records.)
I also tried deleting the product the products with HQL.
This works, however, the products also have a <map> assocation, and the cascade settings are discarded when using HQL. So for this HQL is not a solution either.
The only solution I see right now is using plain SQL....
Code:
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.query.substitutions">true 1,false 0</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.jdbc.fetch_size">100</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
Code:
<hibernate-mapping default-access="field" >
<class name="entities.Person" table="person">
<id name="id" column="id" access="property">
<generator class="native"/>
</id>
<set name="products" cascade="all-delete-orphan">
<key column="person_id" not-null="true" update="false" />
<one-to-many class="entities.Product"/>
</set>
</class>
</hibernate-mapping>
Code:
<hibernate-mapping default-access="field" >
<class name="entities.Product" table="product">
<id name="id" column="id" access="property">
<generator class="native"/>
</id>
<property name="name" column="name"/>
</class>
</hibernate-mapping>