2

客户实体(父实体)

@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
...
}

Customer实体中,我使用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")
4

2 回答 2

2

根据 JPA 规范,批量删除操作没有级联:

4.10 批量更新和删除操作

...

删除操作仅适用于指定类及其子类的实体。它不会级联到相关实体。

...

如果您想从级联中受益,请加载实体然后调用EntityManager#remove(Object)它。

于 2010-08-04T21:24:24.117 回答
0

尝试:

@Inject
EntityManager em;

Customer customer =...;
em.remove(customer);

这总是级联操作。

于 2012-10-28T22:27:25.513 回答