JPA:当父实体被删除时,子实体仍然存在
Customer
实体中的客户实体(父实体)
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(mappedBy="customer", cascade=CascadeType.ALL)
private List<Facility> facilities;
//Setter and Getter for name and facilities
public void addFacility(Facility facility){
if(this.facilities == null){
this.facilities = new ArrayList<Facility>();
}
this.facilities.add(facility);
facility.setCustomer(this);
}
}
设施实体(子实体)
@Entity
public class Facility {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name="CUSTOMER_FK")
private Customer customer;
private String name;
//Setter and Getter, equals and hashcode
...
}
,我使用 CascadeType.ALL
,但是当我删除客户时,关联的设施仍然存在。 删除 customer
Query query = em.createNamedQuery("Customer.delete");
query.setParameter("id", customerId);
query.executeUpdate();
我按以下位置
@NamedQuery(name="Customer.delete", query="delete from Customer c where c.id = :id")
Customer Entity (Parent Entity)
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(mappedBy="customer", cascade=CascadeType.ALL)
private List<Facility> facilities;
//Setter and Getter for name and facilities
public void addFacility(Facility facility){
if(this.facilities == null){
this.facilities = new ArrayList<Facility>();
}
this.facilities.add(facility);
facility.setCustomer(this);
}
}
Facility Entity (Child Entity)
@Entity
public class Facility {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name="CUSTOMER_FK")
private Customer customer;
private String name;
//Setter and Getter, equals and hashcode
...
}
in Customer
entity, I use CascadeType.ALL
, however when I remove a customer, the associated facilities are still there. I delete customer
by
Query query = em.createNamedQuery("Customer.delete");
query.setParameter("id", customerId);
query.executeUpdate();
where
@NamedQuery(name="Customer.delete", query="delete from Customer c where c.id = :id")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 JPA 规范,批量删除操作不会级联:
如果您想从级联中受益,请加载实体,然后对其调用 EntityManager#remove(Object) 。
Bulk delete operations are not cascaded, per JPA specification:
If you want to benefit from cascading, load the entity and then call
EntityManager#remove(Object)
on it.尝试使用:
@Inject
EntityManager em;
客户客户 =...;
em.remove(customer);
这总是级联操作。
Try with:
@Inject
EntityManager em;
Customer customer =...;
em.remove(customer);
This always cascades operations.