views:

26

answers:

1

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")
+2  A: 

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.

Pascal Thivent
Does `orphanRemoval` attribute help solving the problem?
Harry Pham
@Harry If you want to cascade the delete to the children, use `em.remove()`, not a bulk delete operation. `orphanRemoval` won't solve anything, you just need to change your approach.
Pascal Thivent
Thank you. I hope that you was not annoyed by my stupid question. I got it working correctly. If you dont mind, will you explain a bit to me about `orphanRemoval`. Here is an example from the documentation: `if an order has many line items, and one of the line items is removed from the order, the removed line item is considered an orphan. If orphanRemoval is set to true, the line item entity will be deleted when the line item is removed from the order.`. So seems to me like orphanRemoval is like a garbage collector. It release memory of entity which being removed. Right?
Harry Pham
@Harry No, no, don't worry (I just didn't know what to add to make things more clear). Regarding `orphanRemoval` (not easy to discuss that in a small comment box), setting `orphanRemoval=true` in your example will make the JPA provider perform a **database DELETE** of the line item removed from the collection. Without it, the line item would remain in the table (but without being "linked" to any order, being thus an "orphan" record).
Pascal Thivent
tyvm, it make sense to me
Harry Pham