我在Product
和Product_Order
中有一对多的关系。我想使用级联,这样在从产品中删除产品记录时,它不会从Product_Order
删除已保存的记录,而只是在子表中将它们变为孤儿。我应该使用什么以及如何使用?
public class Product implements Serializable {
@OneToMany(mappedBy="product")
private Set<ProductOrder> productOrder;
答案 0 :(得分:1)
以下代码片段形式为hibernate CascadeType 类。 选项全部包括以下所有操作。
您可以清楚地看到, DELETE 对应于Hibernate而不是JPA,因此JPA使用(orphanRemoval = true)选项删除子记录。
来自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
}
来自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
}
希望现在事情应该很清楚
答案 1 :(得分:1)
在ProductDao类的delete()中,您需要设置productOrder,遍历每个订单,将每个订单的产品设置为null,在数据库中更新它。像这样:
for (ProductOrder order : product.getProductOrder())
{
order.setProduct(null);
ProductOrderDao.update(order);
}
session.delete(product);
这可能有效,但我不建议这样做。在数据库中保留孤立对象可能会使其变得混乱,因此将来很难管理。