Merge pull request #10216 from emyasa/BAEL-4643

BAEL-4643: JPA CascadeType.REMOVE vs orphanRemoval
This commit is contained in:
Jonathan Cook
2020-11-11 11:46:00 +01:00
committed by GitHub
6 changed files with 315 additions and 21 deletions
@@ -0,0 +1,45 @@
package com.baeldung.jpa.removal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.util.Objects;
@Entity
public class LineItem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne
private OrderRequest orderRequest;
public LineItem(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
LineItem lineItem = (LineItem) o;
return Objects.equals(id, lineItem.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
protected LineItem() {
}
}
@@ -0,0 +1,43 @@
package com.baeldung.jpa.removal;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import java.util.List;
@Entity
public class OrderRequest {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(cascade = { CascadeType.REMOVE, CascadeType.PERSIST })
private ShipmentInfo shipmentInfo;
@OneToMany(orphanRemoval = true, cascade = CascadeType.PERSIST, mappedBy = "orderRequest")
private List<LineItem> lineItems;
public OrderRequest(ShipmentInfo shipmentInfo) {
this.shipmentInfo = shipmentInfo;
}
public OrderRequest(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
public void removeLineItem(LineItem lineItem) {
lineItems.remove(lineItem);
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
protected OrderRequest() {
}
}
@@ -0,0 +1,23 @@
package com.baeldung.jpa.removal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class ShipmentInfo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public ShipmentInfo(String name) {
this.name = name;
}
protected ShipmentInfo() {
}
}