문제

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")
도움이 되었습니까?

해결책

Bulk delete operations are not cascaded, per JPA specification:

4.10 Bulk Update and Delete Operations

...

A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

...

If you want to benefit from cascading, load the entity and then call EntityManager#remove(Object) on it.

다른 팁

Try with:

@Inject
EntityManager em;

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

This always cascades operations.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top