Reputation: 743
I have a one-to-many relationship in Product
and Product_Order
. I want to use cascade such that on deleting Product record from Product it does not delete already saved record from Product_Order
, but just make them orphan in child table. What should I use and how?
public class Product implements Serializable {
@OneToMany(mappedBy="product")
private Set<ProductOrder> productOrder;
Upvotes: 1
Views: 1199
Reputation: 18875
In your delete() of your ProductDao class, you will need to get the productOrder set, iterate through each order, set each order's product to null, update it in database. Something like this:
for (ProductOrder order : product.getProductOrder())
{
order.setProduct(null);
ProductOrderDao.update(order);
}
session.delete(product);
This may work, but I don't recommend this. Leaving orphan objects in your database will probably make it messy and therefore hard to manage in future.
Upvotes: 1
Reputation: 26067
Below code snippet form hibernate CascadeType class. Option All includes all the below operations.
As you can clearly see, DELETE corresponds to Hibernate and not JPA, so JPA uses (orphanRemoval=true) option to delete child record.
From Hibernate
public enum CascadeType {
/**
* Includes all types listed here.
*/
ALL,
/**
* Corresponds to {@link javax.persistence.CascadeType#PERSIST}.
*/
PERSIST,
/**
* Corresponds to {@link javax.persistence.CascadeType#MERGE}.
*/
MERGE,
/**
* Corresponds to {@link javax.persistence.CascadeType#REMOVE}.
*/
REMOVE,
/**
* Corresponds to {@link javax.persistence.CascadeType#REFRESH}.
*/
REFRESH,
/**
* Corresponds to the Hibernate native DELETE action.
*/
DELETE,
/**
* Corresponds to the Hibernate native SAVE_UPDATE (direct reattachment) action.
*/
SAVE_UPDATE,
/**
* Corresponds to the Hibernate native REPLICATE action.
*/
REPLICATE,
/**
* Hibernate originally handled orphan removal as a specialized cascade.
*
* @deprecated use @OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true)
*/
@Deprecated
DELETE_ORPHAN,
/**
* Corresponds to the Hibernate native LOCK action.
*/
LOCK,
/**
* JPA originally planned on calling DETACH EVICT.
*
* @deprecated use javax.persistence.CascadeType.DETACH
*/
@Deprecated
EVICT,
/**
* Corresponds to {@link javax.persistence.CascadeType#REFRESH}.
*/
DETACH
}
From JPA
public enum CascadeType {
/** Cascade all operations */
ALL,
/** Cascade persist operation */
PERSIST,
/** Cascade merge operation */
MERGE,
/** Cascade remove operation */
REMOVE,
/** Cascade refresh operation */
REFRESH,
/**
* Cascade detach operation
*
* @since Java Persistence 2.0
*
*/
DETACH
}
Hope now things should be much clear
Upvotes: 1