Add cascade-types module: JPA cascade types and orphanRemoval on Hibernate 7.4.15.Final and 8.0.0.CR1 (incident reproduced in three schemas, cascade matrix, @OnDelete, delete order)
Plain Hibernate on H2, 14 tests, transcripts in cascade-types/output (h7 and h8). No docs folder. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5sy5qAYYdeYeS1xLW
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String line1;
|
||||
|
||||
protected Address() {
|
||||
}
|
||||
|
||||
public Address(String line1) {
|
||||
this.line1 = line1;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Agent {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
protected Agent() {
|
||||
}
|
||||
|
||||
public Agent(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
/** Called AppUser, not User, because USER is a reserved word in H2 and PostgreSQL. A shared parent: many projects point at one user. */
|
||||
@Entity
|
||||
public class AppUser {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
protected AppUser() {
|
||||
}
|
||||
|
||||
public AppUser(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** cascade = REMOVE (plus PERSIST) but no orphanRemoval: deleting the basket deletes items, unlinking an item does not. */
|
||||
@Entity
|
||||
public class Basket {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(mappedBy = "basket", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
|
||||
private List<BasketItem> items = new ArrayList<>();
|
||||
|
||||
public BasketItem add(String name) {
|
||||
BasketItem item = new BasketItem(this, name);
|
||||
items.add(item);
|
||||
return item;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<BasketItem> getItems() {
|
||||
return items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class BasketItem {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "basket_id")
|
||||
private Basket basket;
|
||||
|
||||
protected BasketItem() {
|
||||
}
|
||||
|
||||
BasketItem(Basket basket, String name) {
|
||||
this.basket = basket;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
/** Parent in a mandatory relationship: every Card must belong to a board, so a card's foreign key can never be nulled. */
|
||||
@Entity
|
||||
public class Board {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
protected Board() {
|
||||
}
|
||||
|
||||
public Board(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Card {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToOne(optional = false)
|
||||
@JoinColumn(name = "board_id", nullable = false)
|
||||
private Board board;
|
||||
|
||||
protected Card() {
|
||||
}
|
||||
|
||||
public Card(String title, Board board) {
|
||||
this.title = title;
|
||||
this.board = board;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Comment {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String text;
|
||||
|
||||
// No cascade: the writer outlives any individual comment
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "author_id")
|
||||
private Writer author;
|
||||
|
||||
protected Comment() {
|
||||
}
|
||||
|
||||
Comment(Writer author, String text) {
|
||||
this.author = author;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
/** Bad: deleting any comment tries to delete its author. */
|
||||
@Entity
|
||||
public class CommentBad {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String text;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "author_id")
|
||||
private Writer author;
|
||||
|
||||
protected CommentBad() {
|
||||
}
|
||||
|
||||
public CommentBad(Writer author, String text) {
|
||||
this.author = author;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinTable;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/** Bad: cascade ALL on a @ManyToMany includes REMOVE, so deleting the course deletes its students. */
|
||||
@Entity
|
||||
public class CourseBad {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToMany(cascade = CascadeType.ALL)
|
||||
@JoinTable(name = "course_bad_students",
|
||||
joinColumns = @JoinColumn(name = "course_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "student_id"))
|
||||
private Set<Student> students = new HashSet<>();
|
||||
|
||||
protected CourseBad() {
|
||||
}
|
||||
|
||||
public CourseBad(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Set<Student> getStudents() {
|
||||
return students;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.JoinTable;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/** Aggregation: PERSIST and MERGE so saving a course saves new students; deleting a course removes only the join rows. */
|
||||
@Entity
|
||||
public class CourseGood {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||
@JoinTable(name = "course_good_students",
|
||||
joinColumns = @JoinColumn(name = "course_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "student_id"))
|
||||
private Set<Student> students = new HashSet<>();
|
||||
|
||||
protected CourseGood() {
|
||||
}
|
||||
|
||||
public CourseGood(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Set<Student> getStudents() {
|
||||
return students;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Doc {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "folder_id")
|
||||
private Folder folder;
|
||||
|
||||
protected Doc() {
|
||||
}
|
||||
|
||||
Doc(Folder folder, String title) {
|
||||
this.folder = folder;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** orphanRemoval = true and cascade = PERSIST only. There is deliberately no REMOVE here; see T03_OrphanVsRemoveTest. */
|
||||
@Entity
|
||||
public class Folder {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(mappedBy = "folder", cascade = CascadeType.PERSIST, orphanRemoval = true)
|
||||
private List<Doc> docs = new ArrayList<>();
|
||||
|
||||
public Doc add(String title) {
|
||||
Doc d = new Doc(this, title);
|
||||
docs.add(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<Doc> getDocs() {
|
||||
return docs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Composition: a line is meaningless without its invoice, so the invoice owns the line's whole lifecycle. */
|
||||
@Entity
|
||||
public class Invoice {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String number;
|
||||
|
||||
@OneToMany(mappedBy = "invoice",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true)
|
||||
private List<InvoiceLine> lines = new ArrayList<>();
|
||||
|
||||
protected Invoice() {
|
||||
}
|
||||
|
||||
public Invoice(String number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public InvoiceLine addLine(String description) {
|
||||
InvoiceLine line = new InvoiceLine(this, description);
|
||||
lines.add(line);
|
||||
return line;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public List<InvoiceLine> getLines() {
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** Replaces the collection object itself: the classic way to break orphanRemoval. */
|
||||
public void setLines(List<InvoiceLine> lines) {
|
||||
this.lines = lines;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
/** The child side: no cascade back to the invoice, because a line must never decide the invoice's fate. */
|
||||
@Entity
|
||||
public class InvoiceLine {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String description;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "invoice_id")
|
||||
private Invoice invoice;
|
||||
|
||||
protected InvoiceLine() {
|
||||
}
|
||||
|
||||
InvoiceLine(Invoice invoice, String description) {
|
||||
this.invoice = invoice;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Leaf {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String label;
|
||||
|
||||
protected Leaf() {
|
||||
}
|
||||
|
||||
public Leaf(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
public void setLabel(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
|
||||
/** Database-level cascade: no JPA cascade at all; the foreign key says ON DELETE CASCADE and Hibernate trusts it. */
|
||||
@Entity
|
||||
public class Ledger {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(mappedBy = "ledger")
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
private List<LedgerEntry> entries = new ArrayList<>();
|
||||
|
||||
public LedgerEntry add(String memo) {
|
||||
LedgerEntry e = new LedgerEntry(this, memo);
|
||||
entries.add(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<LedgerEntry> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class LedgerEntry {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String memo;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "ledger_id")
|
||||
private Ledger ledger;
|
||||
|
||||
protected LedgerEntry() {
|
||||
}
|
||||
|
||||
LedgerEntry(Ledger ledger, String memo) {
|
||||
this.ledger = ledger;
|
||||
this.memo = memo;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
/** Two @OneToOne associations, two different answers: an owned profile cascades, a shared billing address does not. */
|
||||
@Entity
|
||||
public class Person {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
/** Owned: the profile only makes sense attached to this person. */
|
||||
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private Profile profile;
|
||||
|
||||
/** Shared: several people may live at, and be billed to, the same address. */
|
||||
@OneToOne
|
||||
private Address billingAddress;
|
||||
|
||||
protected Person() {
|
||||
}
|
||||
|
||||
public Person(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Profile getProfile() {
|
||||
return profile;
|
||||
}
|
||||
|
||||
public void setProfile(Profile profile) {
|
||||
this.profile = profile;
|
||||
}
|
||||
|
||||
public Address getBillingAddress() {
|
||||
return billingAddress;
|
||||
}
|
||||
|
||||
public void setBillingAddress(Address billingAddress) {
|
||||
this.billingAddress = billingAddress;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
/** One association per cascade type, all pointing at {@link Leaf}, so a test can see which operation travels along which one. */
|
||||
@Entity
|
||||
public class Probe {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@OneToOne(cascade = CascadeType.PERSIST)
|
||||
private Leaf onPersist;
|
||||
|
||||
@OneToOne(cascade = CascadeType.MERGE)
|
||||
private Leaf onMerge;
|
||||
|
||||
@OneToOne(cascade = CascadeType.REMOVE)
|
||||
private Leaf onRemove;
|
||||
|
||||
@OneToOne(cascade = CascadeType.REFRESH)
|
||||
private Leaf onRefresh;
|
||||
|
||||
@OneToOne(cascade = CascadeType.DETACH)
|
||||
private Leaf onDetach;
|
||||
|
||||
@OneToOne(cascade = CascadeType.ALL)
|
||||
private Leaf onAll;
|
||||
|
||||
@OneToOne
|
||||
private Leaf none;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Leaf get(String field) {
|
||||
return switch (field) {
|
||||
case "onPersist" -> onPersist;
|
||||
case "onMerge" -> onMerge;
|
||||
case "onRemove" -> onRemove;
|
||||
case "onRefresh" -> onRefresh;
|
||||
case "onDetach" -> onDetach;
|
||||
case "onAll" -> onAll;
|
||||
case "none" -> none;
|
||||
default -> throw new IllegalArgumentException(field);
|
||||
};
|
||||
}
|
||||
|
||||
public void set(String field, Leaf leaf) {
|
||||
switch (field) {
|
||||
case "onPersist" -> onPersist = leaf;
|
||||
case "onMerge" -> onMerge = leaf;
|
||||
case "onRemove" -> onRemove = leaf;
|
||||
case "onRefresh" -> onRefresh = leaf;
|
||||
case "onDetach" -> onDetach = leaf;
|
||||
case "onAll" -> onAll = leaf;
|
||||
case "none" -> none = leaf;
|
||||
default -> throw new IllegalArgumentException(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Profile {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String bio;
|
||||
|
||||
protected Profile() {
|
||||
}
|
||||
|
||||
public Profile(String bio) {
|
||||
this.bio = bio;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
/** The startup's mapping: cascade = ALL on a @ManyToOne to a shared parent. Do not copy. */
|
||||
@Entity
|
||||
public class ProjectBad {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "owner_id")
|
||||
private AppUser owner;
|
||||
|
||||
protected ProjectBad() {
|
||||
}
|
||||
|
||||
public ProjectBad(String title, AppUser owner) {
|
||||
this.title = title;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
|
||||
/** The same bad mapping on a schema whose foreign key says ON DELETE CASCADE: the "worst case" of the incident. */
|
||||
@Entity
|
||||
public class ProjectBadDb {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "owner_id")
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
private AppUser owner;
|
||||
|
||||
protected ProjectBadDb() {
|
||||
}
|
||||
|
||||
public ProjectBadDb(String title, AppUser owner) {
|
||||
this.title = title;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
/** The fix: no cascade on the shared parent. The user's lifecycle is independent of any one project. */
|
||||
@Entity
|
||||
public class ProjectGood {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
// No cascade: the AppUser lifecycle is independent of the project lifecycle
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "owner_id")
|
||||
private AppUser owner;
|
||||
|
||||
protected ProjectGood() {
|
||||
}
|
||||
|
||||
public ProjectGood(String title, AppUser owner) {
|
||||
this.title = title;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
/** Independent of any course: a student keeps an account and other enrolments when one course disappears. */
|
||||
@Entity
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
protected Student() {
|
||||
}
|
||||
|
||||
public Student(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
/** The one legitimate use of cascade on a @ManyToOne: creating the parent in the same unit of work as its first child. Never REMOVE. */
|
||||
@Entity
|
||||
public class Ticket {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String subject;
|
||||
|
||||
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||
private Agent agent;
|
||||
|
||||
protected Ticket() {
|
||||
}
|
||||
|
||||
public Ticket(String subject, Agent agent) {
|
||||
this.subject = subject;
|
||||
this.agent = agent;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.hibernate.annotations.OnDelete;
|
||||
import org.hibernate.annotations.OnDeleteAction;
|
||||
|
||||
/** The common idiom: JPA cascade = REMOVE together with @OnDelete, so Hibernate cascades in memory and leaves the row deletes to the database. */
|
||||
@Entity
|
||||
public class Vault {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(mappedBy = "vault", cascade = CascadeType.ALL)
|
||||
@OnDelete(action = OnDeleteAction.CASCADE)
|
||||
private List<VaultEntry> entries = new ArrayList<>();
|
||||
|
||||
public VaultEntry add(String memo) {
|
||||
VaultEntry e = new VaultEntry(this, memo);
|
||||
entries.add(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<VaultEntry> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class VaultEntry {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String memo;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "vault_id")
|
||||
private Vault vault;
|
||||
|
||||
protected VaultEntry() {
|
||||
}
|
||||
|
||||
VaultEntry(Vault vault, String memo) {
|
||||
this.vault = vault;
|
||||
this.memo = memo;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Cascade ALL on the owned children is correct: a writer's comments die with the writer's account. */
|
||||
@Entity
|
||||
public class Writer {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "author",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true)
|
||||
private List<Comment> comments = new ArrayList<>();
|
||||
|
||||
protected Writer() {
|
||||
}
|
||||
|
||||
public Writer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Comment comment(String text) {
|
||||
Comment c = new Comment(this, text);
|
||||
comments.add(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<Comment> getComments() {
|
||||
return comments;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.resource.jdbc.spi.StatementInspector;
|
||||
|
||||
/** Plain Hibernate bootstrap on an in-memory H2 (no Spring, no persistence.xml) plus helpers that record the SQL Hibernate sends. */
|
||||
final class Db implements AutoCloseable {
|
||||
|
||||
/** Every SQL string Hibernate prepares, in order (raw JDBC issued by the tests is not recorded). */
|
||||
private static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
public static class Recorder implements StatementInspector {
|
||||
@Override
|
||||
public String inspect(String sql) {
|
||||
synchronized (LOG) {
|
||||
LOG.add(sql.replaceAll("\\s+", " ").trim());
|
||||
}
|
||||
return sql;
|
||||
}
|
||||
}
|
||||
|
||||
private final SessionFactory sf;
|
||||
|
||||
private Db(SessionFactory sf) {
|
||||
this.sf = sf;
|
||||
}
|
||||
|
||||
static Db open(Class<?>... entities) {
|
||||
return open(Map.of(), entities);
|
||||
}
|
||||
|
||||
static Db open(Map<String, String> extra, Class<?>... entities) {
|
||||
StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder()
|
||||
.applySetting("hibernate.connection.url", "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1")
|
||||
.applySetting("hibernate.connection.username", "sa")
|
||||
.applySetting("hibernate.hbm2ddl.auto", "create-drop")
|
||||
.applySetting("hibernate.generate_statistics", "true")
|
||||
.applySetting("hibernate.session_factory.statement_inspector", Recorder.class.getName());
|
||||
extra.forEach(b::applySetting);
|
||||
StandardServiceRegistry registry = b.build();
|
||||
MetadataSources sources = new MetadataSources(registry);
|
||||
for (Class<?> e : entities) {
|
||||
sources.addAnnotatedClass(e);
|
||||
}
|
||||
return new Db(sources.buildMetadata().buildSessionFactory());
|
||||
}
|
||||
|
||||
SessionFactory sf() {
|
||||
return sf;
|
||||
}
|
||||
|
||||
/** Runs {@code work} in its own session and transaction. */
|
||||
<T> T tx(Function<Session, T> work) {
|
||||
try (Session s = sf.openSession()) {
|
||||
var t = s.beginTransaction();
|
||||
try {
|
||||
T r = work.apply(s);
|
||||
t.commit();
|
||||
return r;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
if (t.isActive()) {
|
||||
t.rollback();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void txv(Consumer<Session> work) {
|
||||
tx(s -> {
|
||||
work.accept(s);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs the action and returns the SQL Hibernate prepared while it ran. */
|
||||
static List<String> sql(Runnable action) {
|
||||
synchronized (LOG) {
|
||||
LOG.clear();
|
||||
}
|
||||
action.run();
|
||||
synchronized (LOG) {
|
||||
return new ArrayList<>(LOG);
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw JDBC query, each row rendered as {@code a | b | c}. */
|
||||
List<String> rows(String sql) {
|
||||
return tx(s -> s.doReturningWork(cn -> {
|
||||
List<String> out = new ArrayList<>();
|
||||
try (var st = cn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
|
||||
ResultSetMetaData md = rs.getMetaData();
|
||||
while (rs.next()) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (int i = 1; i <= md.getColumnCount(); i++) {
|
||||
if (i > 1) {
|
||||
b.append(" | ");
|
||||
}
|
||||
b.append(rs.getObject(i));
|
||||
}
|
||||
out.add(b.toString());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}));
|
||||
}
|
||||
|
||||
/** Raw JDBC statement (DDL or DML), invisible to the SQL recorder. */
|
||||
void exec(String sql) {
|
||||
txv(s -> s.doWork(cn -> {
|
||||
try (var st = cn.createStatement()) {
|
||||
st.execute(sql);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
long count(String table) {
|
||||
return Long.parseLong(rows("select count(*) from " + table).get(0));
|
||||
}
|
||||
|
||||
/** The foreign keys of one table with their ON DELETE rule, straight from H2's information schema. */
|
||||
List<String> foreignKeys(String table) {
|
||||
return rows("select tc.constraint_name, rc.delete_rule from information_schema.table_constraints tc "
|
||||
+ "join information_schema.referential_constraints rc on rc.constraint_name = tc.constraint_name "
|
||||
+ "and rc.constraint_schema = tc.constraint_schema "
|
||||
+ "where tc.table_name = '" + table.toUpperCase() + "' and tc.constraint_type = 'FOREIGN KEY' order by 1");
|
||||
}
|
||||
|
||||
static Throwable root(Throwable t) {
|
||||
while (t.getCause() != null && t.getCause() != t) {
|
||||
t = t.getCause();
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Exception chain on one line, class names only, so transcripts stay stable. */
|
||||
static String chain(Throwable t) {
|
||||
StringBuilder sb = new StringBuilder(t.getClass().getName());
|
||||
Throwable c = t.getCause();
|
||||
while (c != null && c != t) {
|
||||
sb.append(" <- ").append(c.getClass().getName());
|
||||
t = c;
|
||||
c = c.getCause();
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static String firstLine(Throwable t) {
|
||||
return String.valueOf(t.getMessage()).lines().findFirst().orElse("");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (sf.isOpen()) {
|
||||
sf.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Which cascade types exist in the shipped jars, which of them are deprecated, and which internal classes really do the walking. */
|
||||
class T01_ApiShapeTest {
|
||||
|
||||
private static String exists(String className) {
|
||||
try {
|
||||
Class.forName(className);
|
||||
return "present";
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
return "absent";
|
||||
}
|
||||
}
|
||||
|
||||
private static String deprecation(Class<?> c) {
|
||||
Deprecated d = c.getAnnotation(Deprecated.class);
|
||||
return d == null ? "not deprecated" : "deprecated(since=" + d.since() + ", forRemoval=" + d.forRemoval() + ")";
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiShape() {
|
||||
Transcript t = new Transcript("01-api-shape", "Cascade API shape in the shipped jars");
|
||||
|
||||
t.heading("jakarta.persistence.CascadeType constants");
|
||||
var jpa = Arrays.stream(jakarta.persistence.CascadeType.values()).map(Enum::name).toList();
|
||||
t.line(String.join(", ", jpa));
|
||||
|
||||
t.heading("org.hibernate.annotations.CascadeType (Hibernate's own enum)");
|
||||
Class<?> hcs = classOrNull("org.hibernate.annotations.CascadeType");
|
||||
t.line("enum class: " + (hcs == null ? "absent" : "present, " + deprecation(hcs)));
|
||||
String hibernateConstants = "n/a";
|
||||
if (hcs != null) {
|
||||
hibernateConstants = Arrays.stream(hcs.getEnumConstants()).map(Object::toString).toList().toString();
|
||||
t.line("constants: " + hibernateConstants);
|
||||
boolean lock = Arrays.stream(hcs.getFields()).map(Field::getName).anyMatch("LOCK"::equals);
|
||||
t.line("has LOCK: " + lock);
|
||||
}
|
||||
Class<?> cascade = classOrNull("org.hibernate.annotations.Cascade");
|
||||
t.line("@Cascade annotation: " + (cascade == null ? "absent" : "present, " + deprecation(cascade)));
|
||||
|
||||
t.heading("Internal classes that do the cascading (where each lives in this jar)");
|
||||
for (String c : new String[] {"Cascade", "CascadingAction", "CascadingActions", "CascadeStyle", "CascadeStyles", "CascadePoint"}) {
|
||||
t.line(String.format("%-18s org.hibernate.engine.internal/spi: %-8s org.hibernate.cascade.internal/spi: %s", c,
|
||||
exists("org.hibernate.engine.internal." + c).equals("present") || exists("org.hibernate.engine.spi." + c).equals("present") ? "present" : "absent",
|
||||
exists("org.hibernate.cascade.internal." + c).equals("present") || exists("org.hibernate.cascade.spi." + c).equals("present") ? "present" : "absent"));
|
||||
}
|
||||
t.line("CascadeEntityPersister (a name the old article used): " + exists("org.hibernate.persister.entity.CascadeEntityPersister"));
|
||||
t.write();
|
||||
assertThat(jpa).containsExactly("ALL", "PERSIST", "MERGE", "REMOVE", "REFRESH", "DETACH");
|
||||
assertThat(exists("org.hibernate.persister.entity.CascadeEntityPersister")).isEqualTo("absent");
|
||||
if (Transcript.LABEL.equals("h7")) {
|
||||
assertThat(exists("org.hibernate.engine.internal.Cascade")).isEqualTo("present");
|
||||
assertThat(hcs).isNotNull();
|
||||
}
|
||||
else {
|
||||
assertThat(exists("org.hibernate.cascade.internal.Cascade")).isEqualTo("present");
|
||||
assertThat(hcs).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
private static Class<?> classOrNull(String n) {
|
||||
try {
|
||||
return Class.forName(n);
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The smallest working example: invoice + lines with cascade ALL and orphanRemoval. The SQL for persist, unlink one line, and remove. */
|
||||
class T02_CompositionTest {
|
||||
|
||||
@Test
|
||||
void invoiceOwnsItsLines() {
|
||||
Transcript t = new Transcript("02-composition", "Composition: Invoice -> InvoiceLine, cascade = ALL + orphanRemoval = true");
|
||||
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||
t.heading("persist(invoice) with two new lines, lines never persisted explicitly");
|
||||
Long id = db.tx(s -> {
|
||||
Invoice inv = new Invoice("INV-1");
|
||||
inv.addLine("hosting");
|
||||
inv.addLine("support");
|
||||
var sql = Db.sql(() -> {
|
||||
s.persist(inv);
|
||||
s.flush();
|
||||
});
|
||||
t.step("persist(inv); flush()", sql);
|
||||
assertThat(sql).hasSize(3);
|
||||
return inv.getId();
|
||||
});
|
||||
t.line("raw rows: invoice=" + db.count("invoice") + " InvoiceLine=" + db.count("InvoiceLine"));
|
||||
assertThat(db.count("InvoiceLine")).isEqualTo(2);
|
||||
|
||||
t.heading("remove one line from the collection (the invoice stays)");
|
||||
t.step("lines.remove(0); flush()", Db.sql(() -> db.txv(s -> {
|
||||
Invoice inv = s.find(Invoice.class, id);
|
||||
inv.getLines().remove(0);
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: invoice=" + db.count("invoice") + " InvoiceLine=" + db.count("InvoiceLine"));
|
||||
assertThat(db.count("invoice")).isEqualTo(1);
|
||||
assertThat(db.count("InvoiceLine")).isEqualTo(1);
|
||||
|
||||
t.heading("remove the invoice");
|
||||
t.step("remove(find(Invoice)); flush()", Db.sql(() -> db.txv(s -> {
|
||||
s.remove(s.find(Invoice.class, id));
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: invoice=" + db.count("invoice") + " InvoiceLine=" + db.count("InvoiceLine"));
|
||||
assertThat(db.count("invoice")).isZero();
|
||||
assertThat(db.count("InvoiceLine")).isZero();
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** cascade = REMOVE and orphanRemoval = true fire on different triggers. Three mappings, two triggers. */
|
||||
class T03_OrphanVsRemoveTest {
|
||||
|
||||
@Test
|
||||
void unlinkingAChild() {
|
||||
Transcript t = new Transcript("03-orphan-vs-remove", "orphanRemoval vs cascade = REMOVE");
|
||||
try (Db db = Db.open(Basket.class, BasketItem.class, Folder.class, Doc.class, Invoice.class, InvoiceLine.class)) {
|
||||
|
||||
t.heading("Trigger 1: child removed from the parent's collection, parent kept");
|
||||
Long basketId = db.tx(s -> {
|
||||
Basket b = new Basket();
|
||||
b.add("keyboard");
|
||||
b.add("mouse");
|
||||
s.persist(b);
|
||||
return b.getId();
|
||||
});
|
||||
t.step("Basket (cascade = {PERSIST, REMOVE}, no orphanRemoval): items.remove(0); flush()", Db.sql(() -> db.txv(s -> {
|
||||
s.find(Basket.class, basketId).getItems().remove(0);
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: BasketItem=" + db.count("BasketItem") + " (still 2: nothing was deleted)");
|
||||
assertThat(db.count("BasketItem")).isEqualTo(2);
|
||||
|
||||
Long invoiceId = db.tx(s -> {
|
||||
Invoice inv = new Invoice("INV-7");
|
||||
inv.addLine("a");
|
||||
inv.addLine("b");
|
||||
s.persist(inv);
|
||||
return inv.getId();
|
||||
});
|
||||
t.step("Invoice (cascade = ALL, orphanRemoval = true): lines.remove(0); flush()", Db.sql(() -> db.txv(s -> {
|
||||
s.find(Invoice.class, invoiceId).getLines().remove(0);
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: InvoiceLine=" + db.count("InvoiceLine") + " (now 1: the orphan was deleted)");
|
||||
assertThat(db.count("InvoiceLine")).isEqualTo(1);
|
||||
|
||||
t.heading("Trigger 2: the parent itself is removed");
|
||||
Long folderId = db.tx(s -> {
|
||||
Folder f = new Folder();
|
||||
f.add("a");
|
||||
f.add("b");
|
||||
s.persist(f);
|
||||
return f.getId();
|
||||
});
|
||||
t.line("Folder maps cascade = PERSIST and orphanRemoval = true, and has no REMOVE at all");
|
||||
t.step("remove(folder); flush()", Db.sql(() -> db.txv(s -> {
|
||||
s.remove(s.find(Folder.class, folderId));
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: doc=" + db.count("doc") + " (0: orphanRemoval alone also deletes children when the parent goes)");
|
||||
assertThat(db.count("doc")).isZero();
|
||||
|
||||
t.step("Basket (REMOVE, no orphanRemoval): remove(basket); flush()", Db.sql(() -> db.txv(s -> {
|
||||
s.remove(s.find(Basket.class, basketId));
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: BasketItem=" + db.count("BasketItem") + " basket=" + db.count("basket"));
|
||||
assertThat(db.count("BasketItem")).isZero();
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The startup incident, reproduced: cascade = ALL on a @ManyToOne to a shared parent, in the three ways it plays out. */
|
||||
class T04_IncidentTest {
|
||||
|
||||
/** Runs the action, returns the exception it threw (or null) and records the SQL Hibernate prepared meanwhile. */
|
||||
private static Throwable run(Transcript t, String label, Runnable action) {
|
||||
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||
var sql = Db.sql(() -> {
|
||||
try {
|
||||
action.run();
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
thrown.set(e);
|
||||
}
|
||||
});
|
||||
t.step(label, sql);
|
||||
if (thrown.get() != null) {
|
||||
t.line(" threw: " + Db.chain(thrown.get()));
|
||||
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||
}
|
||||
return thrown.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cascadeAllOnManyToOne() {
|
||||
Transcript t = new Transcript("04-incident", "The incident: cascade = ALL on a @ManyToOne to a shared parent");
|
||||
try (Db db = Db.open(AppUser.class, ProjectBad.class, ProjectBadDb.class, ProjectGood.class)) {
|
||||
|
||||
t.heading("Foreign keys on the project tables (ON DELETE rule as H2 reports it)");
|
||||
t.line("ProjectBad : " + db.foreignKeys("ProjectBad"));
|
||||
t.line("ProjectBadDb : " + db.foreignKeys("ProjectBadDb"));
|
||||
t.line("ProjectGood : " + db.foreignKeys("ProjectGood"));
|
||||
assertThat(db.foreignKeys("ProjectBadDb").get(0)).contains("CASCADE");
|
||||
assertThat(db.foreignKeys("ProjectBad").get(0)).doesNotContain("CASCADE");
|
||||
|
||||
t.heading("1. Testing: every project has its own user");
|
||||
Long pid1 = db.tx(s -> {
|
||||
AppUser u = new AppUser("test-user-1");
|
||||
s.persist(u);
|
||||
ProjectBad p = new ProjectBad("p1", u);
|
||||
s.persist(p);
|
||||
return p.getId();
|
||||
});
|
||||
Throwable e1 = run(t, "remove(project 1); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(ProjectBad.class, pid1));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: AppUser=" + db.count("AppUser") + " ProjectBad=" + db.count("ProjectBad") + " (the user is gone, nothing failed)");
|
||||
assertThat(e1).isNull();
|
||||
assertThat(db.count("AppUser")).isZero();
|
||||
|
||||
t.heading("2. Production, plain schema: the user has two projects");
|
||||
Long pid2 = db.tx(s -> {
|
||||
AppUser u = new AppUser("real-user");
|
||||
s.persist(u);
|
||||
ProjectBad a = new ProjectBad("first", u);
|
||||
ProjectBad b = new ProjectBad("second", u);
|
||||
s.persist(a);
|
||||
s.persist(b);
|
||||
return a.getId();
|
||||
});
|
||||
Throwable e2 = run(t, "remove(first project); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(ProjectBad.class, pid2));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows after rollback: AppUser=" + db.count("AppUser") + " ProjectBad=" + db.count("ProjectBad"));
|
||||
assertThat(e2).isNotNull();
|
||||
assertThat(db.count("ProjectBad")).isEqualTo(2);
|
||||
|
||||
t.heading("3. Production, schema with ON DELETE CASCADE on the foreign key");
|
||||
Long pid3 = db.tx(s -> {
|
||||
AppUser u = new AppUser("real-user-db");
|
||||
s.persist(u);
|
||||
ProjectBadDb a = new ProjectBadDb("first", u);
|
||||
ProjectBadDb b = new ProjectBadDb("second", u);
|
||||
s.persist(a);
|
||||
s.persist(b);
|
||||
return a.getId();
|
||||
});
|
||||
t.line("before: ProjectBadDb=" + db.count("ProjectBadDb"));
|
||||
Throwable e3 = run(t, "remove(first project); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(ProjectBadDb.class, pid3));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: ProjectBadDb=" + db.count("ProjectBadDb") + " (both projects gone, no error)");
|
||||
assertThat(e3).isNull();
|
||||
assertThat(db.count("ProjectBadDb")).isZero();
|
||||
|
||||
t.heading("4. The fix: ProjectGood, no cascade");
|
||||
long usersBefore = db.count("AppUser");
|
||||
Long pid4 = db.tx(s -> {
|
||||
AppUser u = new AppUser("real-user-good");
|
||||
s.persist(u);
|
||||
ProjectGood a = new ProjectGood("first", u);
|
||||
ProjectGood b = new ProjectGood("second", u);
|
||||
s.persist(a);
|
||||
s.persist(b);
|
||||
return a.getId();
|
||||
});
|
||||
Throwable e4 = run(t, "remove(first project); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(ProjectGood.class, pid4));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: ProjectGood=" + db.count("ProjectGood") + " AppUser=" + (db.count("AppUser") - usersBefore) + " new user(s) kept");
|
||||
assertThat(e4).isNull();
|
||||
assertThat(db.count("ProjectGood")).isEqualTo(1);
|
||||
assertThat(db.count("AppUser") - usersBefore).isEqualTo(1);
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void badAndImprovedComment() {
|
||||
Transcript t = new Transcript("04b-comment-author", "Bad -> improved: CommentBad (cascade ALL to the author) vs Comment + Writer.comments");
|
||||
try (Db db = Db.open(Writer.class, Comment.class, CommentBad.class)) {
|
||||
|
||||
t.heading("Bad: a writer with two comments, delete one");
|
||||
Long cid = db.tx(s -> {
|
||||
Writer w = new Writer("ann");
|
||||
s.persist(w);
|
||||
CommentBad a = new CommentBad(w, "first");
|
||||
s.persist(a);
|
||||
s.persist(new CommentBad(w, "second"));
|
||||
return a.getId();
|
||||
});
|
||||
Throwable e = run(t, "remove(CommentBad first); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(CommentBad.class, cid));
|
||||
s.flush();
|
||||
}));
|
||||
assertThat(e).isNotNull();
|
||||
t.line("raw rows after rollback: Writer=" + db.count("Writer") + " CommentBad=" + db.count("CommentBad"));
|
||||
|
||||
t.heading("Improved: cascade flows down from Writer to Comment, never up");
|
||||
Long wid = db.tx(s -> {
|
||||
Writer w = new Writer("bob");
|
||||
w.comment("one");
|
||||
w.comment("two");
|
||||
s.persist(w);
|
||||
return w.getId();
|
||||
});
|
||||
Long first = db.rows("select min(id) from Comment").get(0).equals("null") ? null : Long.parseLong(db.rows("select min(id) from Comment").get(0));
|
||||
Throwable e2 = run(t, "remove(Comment one); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(Comment.class, first));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Writer(bob)=" + db.rows("select count(*) from Writer where name = 'bob'").get(0) + " Comment=" + db.count("Comment"));
|
||||
assertThat(e2).isNull();
|
||||
assertThat(db.count("Comment")).isEqualTo(1);
|
||||
|
||||
run(t, "remove(Writer bob); flush() (cascade ALL downward)", () -> db.txv(s -> {
|
||||
s.remove(s.find(Writer.class, wid));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Comment=" + db.count("Comment"));
|
||||
assertThat(db.count("Comment")).isZero();
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** One test per relationship type in the decision tree: @ManyToMany, @OneToOne, and the one legitimate cascade on a @ManyToOne. */
|
||||
class T05_RelationshipsTest {
|
||||
|
||||
private static Throwable run(Transcript t, String label, Runnable action) {
|
||||
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||
var sql = Db.sql(() -> {
|
||||
try {
|
||||
action.run();
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
thrown.set(e);
|
||||
}
|
||||
});
|
||||
t.step(label, sql);
|
||||
if (thrown.get() != null) {
|
||||
t.line(" threw: " + Db.chain(thrown.get()));
|
||||
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||
}
|
||||
return thrown.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void manyToMany() {
|
||||
Transcript t = new Transcript("05a-many-to-many", "@ManyToMany: cascade ALL vs {PERSIST, MERGE}");
|
||||
try (Db db = Db.open(Student.class, CourseBad.class, CourseGood.class)) {
|
||||
|
||||
t.heading("CourseBad (cascade = ALL): one student enrolled in two courses");
|
||||
Long bad1 = db.tx(s -> {
|
||||
Student shared = new Student("shared");
|
||||
CourseBad a = new CourseBad("algebra");
|
||||
CourseBad b = new CourseBad("biology");
|
||||
a.getStudents().add(shared);
|
||||
b.getStudents().add(shared);
|
||||
s.persist(a);
|
||||
s.persist(b);
|
||||
return a.getId();
|
||||
});
|
||||
Throwable e = run(t, "remove(algebra); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(CourseBad.class, bad1));
|
||||
s.flush();
|
||||
}));
|
||||
assertThat(e).isNotNull();
|
||||
t.line("raw rows after rollback: CourseBad=" + db.count("CourseBad") + " Student=" + db.count("Student"));
|
||||
|
||||
t.heading("CourseBad: the same, but the student is only in that one course");
|
||||
Long bad2 = db.tx(s -> {
|
||||
CourseBad c = new CourseBad("chemistry");
|
||||
c.getStudents().add(new Student("solo"));
|
||||
s.persist(c);
|
||||
return c.getId();
|
||||
});
|
||||
long studentsBefore = db.count("Student");
|
||||
Throwable e2 = run(t, "remove(chemistry); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(CourseBad.class, bad2));
|
||||
s.flush();
|
||||
}));
|
||||
assertThat(e2).isNull();
|
||||
t.line("raw rows: Student " + studentsBefore + " -> " + db.count("Student") + " (the student was deleted with the course)");
|
||||
assertThat(db.count("Student")).isEqualTo(studentsBefore - 1);
|
||||
|
||||
t.heading("CourseGood (cascade = {PERSIST, MERGE})");
|
||||
Long good = db.tx(s -> {
|
||||
CourseGood c = new CourseGood("dance");
|
||||
c.getStudents().add(new Student("d1"));
|
||||
c.getStudents().add(new Student("d2"));
|
||||
s.persist(c);
|
||||
return c.getId();
|
||||
});
|
||||
long before = db.count("Student");
|
||||
run(t, "remove(dance); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(CourseGood.class, good));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Student " + before + " -> " + db.count("Student") + " course_good_students=" + db.count("course_good_students"));
|
||||
assertThat(db.count("Student")).isEqualTo(before);
|
||||
assertThat(db.count("course_good_students")).isZero();
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneToOne() {
|
||||
Transcript t = new Transcript("05b-one-to-one", "@OneToOne: an owned profile cascades, a shared address does not");
|
||||
try (Db db = Db.open(Person.class, Profile.class, Address.class)) {
|
||||
|
||||
t.heading("Persisting a person with a new profile and a new, unsaved address");
|
||||
Throwable e = run(t, "persist(person); flush()", () -> db.txv(s -> {
|
||||
Person p = new Person("zed");
|
||||
p.setProfile(new Profile("owned"));
|
||||
p.setBillingAddress(new Address("1 Main St"));
|
||||
s.persist(p);
|
||||
s.flush();
|
||||
}));
|
||||
assertThat(e).isNotNull();
|
||||
t.line("raw rows after rollback: Person=" + db.count("Person") + " Profile=" + db.count("Profile"));
|
||||
|
||||
t.heading("Same, with the shared address persisted first");
|
||||
Long pid = db.tx(s -> {
|
||||
Address a = new Address("1 Main St");
|
||||
s.persist(a);
|
||||
Person p = new Person("zed");
|
||||
p.setProfile(new Profile("owned"));
|
||||
p.setBillingAddress(a);
|
||||
s.persist(p);
|
||||
return p.getId();
|
||||
});
|
||||
t.line("raw rows: Person=" + db.count("Person") + " Profile=" + db.count("Profile") + " Address=" + db.count("Address"));
|
||||
assertThat(db.count("Profile")).isEqualTo(1);
|
||||
|
||||
run(t, "setProfile(null); flush() (orphanRemoval)", () -> db.txv(s -> {
|
||||
s.find(Person.class, pid).setProfile(null);
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Profile=" + db.count("Profile"));
|
||||
assertThat(db.count("Profile")).isZero();
|
||||
|
||||
db.txv(s -> s.find(Person.class, pid).setProfile(new Profile("again")));
|
||||
run(t, "remove(person); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(Person.class, pid));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Person=" + db.count("Person") + " Profile=" + db.count("Profile") + " Address=" + db.count("Address") + " (the address survives)");
|
||||
assertThat(db.count("Profile")).isZero();
|
||||
assertThat(db.count("Address")).isEqualTo(1);
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void manyToOnePersistAndMerge() {
|
||||
Transcript t = new Transcript("05c-many-to-one", "@ManyToOne with cascade = {PERSIST, MERGE}: what it is for, and what it cannot do");
|
||||
try (Db db = Db.open(Ticket.class, Agent.class)) {
|
||||
|
||||
t.heading("New parent created together with its first child");
|
||||
run(t, "persist(new Ticket(.., new Agent())); flush()", () -> db.txv(s -> {
|
||||
s.persist(new Ticket("printer", new Agent("new-agent")));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Ticket=" + db.count("Ticket") + " Agent=" + db.count("Agent"));
|
||||
assertThat(db.count("Agent")).isEqualTo(1);
|
||||
|
||||
t.heading("Parent already exists (a detached Agent): persist vs merge");
|
||||
Agent detached = db.tx(s -> {
|
||||
Agent a = new Agent("existing");
|
||||
s.persist(a);
|
||||
return a;
|
||||
});
|
||||
Throwable e = run(t, "persist(new Ticket(.., detachedAgent)); flush()", () -> db.txv(s -> {
|
||||
s.persist(new Ticket("scanner", detached));
|
||||
s.flush();
|
||||
}));
|
||||
assertThat(e).isNotNull();
|
||||
run(t, "merge(new Ticket(.., detachedAgent)); flush()", () -> db.txv(s -> {
|
||||
s.merge(new Ticket("scanner", detached));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Ticket=" + db.count("Ticket") + " Agent=" + db.count("Agent"));
|
||||
assertThat(db.count("Ticket")).isEqualTo(2);
|
||||
assertThat(db.count("Agent")).isEqualTo(2);
|
||||
|
||||
t.heading("Removing a ticket never touches its agent");
|
||||
Long id = Long.parseLong(db.rows("select min(id) from Ticket").get(0));
|
||||
run(t, "remove(ticket); flush()", () -> db.txv(s -> {
|
||||
s.remove(s.find(Ticket.class, id));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: Ticket=" + db.count("Ticket") + " Agent=" + db.count("Agent"));
|
||||
assertThat(db.count("Agent")).isEqualTo(2);
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** What cascade = REMOVE costs, how a bulk delete changes that, and what a database-level ON DELETE CASCADE leaves behind in memory. */
|
||||
class T06_UnderTheHoodTest {
|
||||
|
||||
static final int N = 1000;
|
||||
|
||||
private static long count(List<String> sql, String prefix) {
|
||||
return sql.stream().filter(s -> s.startsWith(prefix)).count();
|
||||
}
|
||||
|
||||
private static Long invoiceWithLines(Db db) {
|
||||
return db.tx(s -> {
|
||||
Invoice inv = new Invoice("BIG");
|
||||
for (int i = 0; i < N; i++) {
|
||||
inv.addLine("line " + i);
|
||||
}
|
||||
s.persist(inv);
|
||||
return inv.getId();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void cascadeRemoveVersusBulkDelete() {
|
||||
Transcript t = new Transcript("06a-cascade-remove-cost", "Removing an invoice with " + N + " lines: cascade REMOVE vs bulk delete first");
|
||||
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||
|
||||
t.line("effective hibernate.jdbc.batch_size: " + db.sf().unwrap(org.hibernate.engine.spi.SessionFactoryImplementor.class).getSessionFactoryOptions().getJdbcBatchSize());
|
||||
t.heading("A. em.remove(invoice) with cascade = ALL, lines never touched by the code");
|
||||
Long a = invoiceWithLines(db);
|
||||
int[] managed = new int[2];
|
||||
db.sf().getStatistics().clear();
|
||||
var sqlA = Db.sql(() -> db.txv(s -> {
|
||||
Invoice inv = s.find(Invoice.class, a);
|
||||
managed[0] = s.getStatistics().getEntityCount();
|
||||
s.remove(inv);
|
||||
managed[1] = s.getStatistics().getEntityCount();
|
||||
s.flush();
|
||||
}));
|
||||
t.line("entities in the persistence context after find(): " + managed[0]);
|
||||
t.line("entities in the persistence context after remove(): " + managed[1]);
|
||||
long deletedA = db.sf().getStatistics().getEntityDeleteCount();
|
||||
t.line("entities deleted (Hibernate statistics): " + deletedA);
|
||||
t.line("SQL strings prepared: total=" + sqlA.size() + " select=" + count(sqlA, "select") + " delete=" + count(sqlA, "delete"));
|
||||
t.line("first statements:");
|
||||
sqlA.stream().limit(4).forEach(s -> t.line(" sql> " + s));
|
||||
assertThat(managed[0]).isEqualTo(1);
|
||||
assertThat(managed[1]).isEqualTo(N + 1);
|
||||
assertThat(deletedA).isEqualTo(N + 1);
|
||||
if (Transcript.LABEL.equals("h7")) {
|
||||
assertThat(count(sqlA, "delete")).isEqualTo(N + 1);
|
||||
}
|
||||
assertThat(db.count("InvoiceLine")).isZero();
|
||||
|
||||
t.heading("A2. the same removal with hibernate.flush.queue.type=legacy (ignored by 7.x)");
|
||||
try (Db legacy = Db.open(Map.of("hibernate.flush.queue.type", "legacy"), Invoice.class, InvoiceLine.class)) {
|
||||
Long a2 = invoiceWithLines(legacy);
|
||||
var sqlA2 = Db.sql(() -> legacy.txv(s -> {
|
||||
s.remove(s.find(Invoice.class, a2));
|
||||
s.flush();
|
||||
}));
|
||||
t.line("SQL strings prepared: total=" + sqlA2.size() + " select=" + count(sqlA2, "select") + " delete=" + count(sqlA2, "delete"));
|
||||
assertThat(legacy.count("InvoiceLine")).isZero();
|
||||
}
|
||||
|
||||
t.heading("B. bulk delete of the lines first, then remove(getReference(invoice))");
|
||||
Long b = invoiceWithLines(db);
|
||||
int[] managedB = new int[1];
|
||||
db.sf().getStatistics().clear();
|
||||
var sqlB = Db.sql(() -> db.txv(s -> {
|
||||
s.createMutationQuery("delete from InvoiceLine l where l.invoice.id = :id").setParameter("id", b).executeUpdate();
|
||||
Invoice ref = s.getReference(Invoice.class, b);
|
||||
s.remove(ref);
|
||||
managedB[0] = s.getStatistics().getEntityCount();
|
||||
s.flush();
|
||||
}));
|
||||
t.line("entities in the persistence context after remove(): " + managedB[0]);
|
||||
t.line("entities deleted (Hibernate statistics): " + db.sf().getStatistics().getEntityDeleteCount());
|
||||
t.line("SQL strings prepared: total=" + sqlB.size() + " select=" + count(sqlB, "select") + " delete=" + count(sqlB, "delete"));
|
||||
sqlB.forEach(s -> t.line(" sql> " + s));
|
||||
assertThat(db.count("Invoice")).isZero();
|
||||
assertThat(db.count("InvoiceLine")).isZero();
|
||||
assertThat(sqlB).hasSize(4);
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
private static Throwable attempt(Runnable r) {
|
||||
try {
|
||||
r.run();
|
||||
return null;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void databaseCascade() {
|
||||
Transcript t = new Transcript("06b-on-delete-cascade", "@OnDelete(CASCADE): the database deletes the children, Hibernate does not know");
|
||||
try (Db db = Db.open(Ledger.class, LedgerEntry.class, Vault.class, VaultEntry.class, AppUser.class, ProjectGood.class)) {
|
||||
t.line("LedgerEntry foreign key: " + db.foreignKeys("LedgerEntry"));
|
||||
t.line("VaultEntry foreign key: " + db.foreignKeys("VaultEntry"));
|
||||
|
||||
t.heading("1. Ledger: @OnDelete only, children never loaded");
|
||||
Long l1 = db.tx(s -> {
|
||||
Ledger l = new Ledger();
|
||||
l.add("a");
|
||||
l.add("b");
|
||||
l.add("c");
|
||||
s.persist(l);
|
||||
// no JPA cascade on Ledger.entries, so every child is persisted by hand
|
||||
l.getEntries().forEach(s::persist);
|
||||
return l.getId();
|
||||
});
|
||||
t.step("remove(find(Ledger)); flush()", Db.sql(() -> db.txv(s -> {
|
||||
s.remove(s.find(Ledger.class, l1));
|
||||
s.flush();
|
||||
})));
|
||||
t.line("raw rows: Ledger=" + db.count("Ledger") + " LedgerEntry=" + db.count("LedgerEntry"));
|
||||
assertThat(db.count("LedgerEntry")).isZero();
|
||||
|
||||
t.heading("2. Ledger: @OnDelete only, but the entries are already loaded in the session");
|
||||
Long l2 = db.tx(s -> {
|
||||
Ledger l = new Ledger();
|
||||
l.add("a");
|
||||
l.add("b");
|
||||
s.persist(l);
|
||||
l.getEntries().forEach(s::persist);
|
||||
return l.getId();
|
||||
});
|
||||
Throwable[] thrown = new Throwable[1];
|
||||
var sql2 = Db.sql(() -> thrown[0] = attempt(() -> db.txv(s -> {
|
||||
Ledger l = s.find(Ledger.class, l2);
|
||||
l.getEntries().size();
|
||||
s.remove(l);
|
||||
s.flush();
|
||||
})));
|
||||
t.step("find(Ledger); entries.size(); remove(ledger); flush()", sql2);
|
||||
t.line(" threw: " + Db.chain(thrown[0]));
|
||||
t.line(" cause: " + Db.firstLine(Db.root(thrown[0])));
|
||||
assertThat(thrown[0]).isNotNull();
|
||||
|
||||
t.heading("3. Vault: cascade = ALL plus @OnDelete, entries loaded");
|
||||
Long v = db.tx(s -> {
|
||||
Vault vault = new Vault();
|
||||
vault.add("a");
|
||||
vault.add("b");
|
||||
vault.add("c");
|
||||
s.persist(vault);
|
||||
return vault.getId();
|
||||
});
|
||||
try (var s = db.sf().openSession()) {
|
||||
var tx = s.beginTransaction();
|
||||
Vault vault = s.find(Vault.class, v);
|
||||
VaultEntry first = vault.getEntries().get(0);
|
||||
Long firstId = first.getId();
|
||||
var sql3 = Db.sql(() -> {
|
||||
s.remove(vault);
|
||||
s.flush();
|
||||
});
|
||||
t.step("find(Vault); remove(vault); flush()", sql3);
|
||||
tx.commit();
|
||||
t.line("raw rows after commit: Vault=" + db.count("Vault") + " VaultEntry=" + db.count("VaultEntry"));
|
||||
t.line("same session, contains(firstEntry) after commit: " + s.contains(first));
|
||||
t.line("same session, find(VaultEntry " + "first" + "): " + (s.find(VaultEntry.class, firstId) == null ? "null" : "still returns an entity"));
|
||||
assertThat(sql3).anyMatch(x -> x.startsWith("delete from Vault "));
|
||||
assertThat(db.count("VaultEntry")).isZero();
|
||||
}
|
||||
|
||||
t.heading("4. A cascade that only exists in the schema: the mapping (ProjectGood -> AppUser) says nothing about it");
|
||||
String fk = db.rows("select constraint_name from information_schema.table_constraints where table_name = 'PROJECTGOOD' and constraint_type = 'FOREIGN KEY'").get(0);
|
||||
db.exec("alter table ProjectGood drop constraint " + fk);
|
||||
db.exec("alter table ProjectGood add constraint fk_project_owner foreign key (owner_id) references AppUser (id) on delete cascade");
|
||||
t.line("ProjectGood foreign key now: " + db.foreignKeys("ProjectGood"));
|
||||
Long[] ids = db.tx(s -> {
|
||||
AppUser u = new AppUser("schema-cascade");
|
||||
s.persist(u);
|
||||
ProjectGood p = new ProjectGood("p", u);
|
||||
s.persist(p);
|
||||
return new Long[] {u.getId(), p.getId()};
|
||||
});
|
||||
try (var s = db.sf().openSession()) {
|
||||
var tx = s.beginTransaction();
|
||||
AppUser u = s.find(AppUser.class, ids[0]);
|
||||
ProjectGood p = s.find(ProjectGood.class, ids[1]);
|
||||
var sql4 = Db.sql(() -> s.createNativeMutationQuery("delete from AppUser where id = ?1").setParameter(1, ids[0]).executeUpdate());
|
||||
t.step("native: delete from AppUser where id = ?", sql4);
|
||||
tx.commit();
|
||||
t.line("raw rows: AppUser(id)=" + db.rows("select count(*) from AppUser where id = " + ids[0]).get(0) + " ProjectGood(id)=" + db.rows("select count(*) from ProjectGood where id = " + ids[1]).get(0));
|
||||
var sql5 = Db.sql(() -> t.line("same session, find(ProjectGood) -> " + (s.find(ProjectGood.class, ids[1]) == null ? "null" : "still returns the deleted project")));
|
||||
t.line("SQL issued by that find: " + sql5.size());
|
||||
t.line("same session, contains(project): " + s.contains(p));
|
||||
assertThat(s.contains(p)).isTrue();
|
||||
assertThat(sql5).isEmpty();
|
||||
s.clear();
|
||||
t.line("after session.clear(), find(ProjectGood) -> " + (s.find(ProjectGood.class, ids[1]) == null ? "null" : "entity"));
|
||||
}
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Ways orphanRemoval goes wrong: replacing the collection object, and merge() on a parent whose collection was emptied. */
|
||||
class T07_OrphanFailureModesTest {
|
||||
|
||||
private static Throwable run(Transcript t, String label, Runnable action) {
|
||||
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||
var sql = Db.sql(() -> {
|
||||
try {
|
||||
action.run();
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
thrown.set(e);
|
||||
}
|
||||
});
|
||||
t.step(label, sql);
|
||||
if (thrown.get() != null) {
|
||||
t.line(" threw: " + Db.chain(thrown.get()));
|
||||
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||
}
|
||||
return thrown.get();
|
||||
}
|
||||
|
||||
private static Long invoice(Db db, String number, int lines) {
|
||||
return db.tx(s -> {
|
||||
Invoice inv = new Invoice(number);
|
||||
for (int i = 0; i < lines; i++) {
|
||||
inv.addLine("l" + i);
|
||||
}
|
||||
s.persist(inv);
|
||||
return inv.getId();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingTheCollection() {
|
||||
Transcript t = new Transcript("07a-replace-collection", "orphanRemoval: replacing the collection instead of changing it");
|
||||
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||
Long id = invoice(db, "R-1", 2);
|
||||
|
||||
t.heading("setLines(new ArrayList<>()) on a managed invoice");
|
||||
Throwable e = run(t, "setLines(new ArrayList<>()); flush()", () -> db.txv(s -> {
|
||||
s.find(Invoice.class, id).setLines(new ArrayList<>());
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows after rollback: InvoiceLine=" + db.count("InvoiceLine"));
|
||||
assertThat(e).isNotNull();
|
||||
assertThat(db.count("InvoiceLine")).isEqualTo(2);
|
||||
|
||||
t.heading("The safe way: clear() the existing collection");
|
||||
Throwable ok = run(t, "getLines().clear(); flush()", () -> db.txv(s -> {
|
||||
s.find(Invoice.class, id).getLines().clear();
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: InvoiceLine=" + db.count("InvoiceLine"));
|
||||
assertThat(ok).isNull();
|
||||
assertThat(db.count("InvoiceLine")).isZero();
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeOfAnEmptiedCollection() {
|
||||
Transcript t = new Transcript("07b-merge-emptied-collection", "orphanRemoval and merge(): managed parent, emptied collection (reported as a 6.6 -> 7.x regression)");
|
||||
try (Db db = Db.open(Invoice.class, InvoiceLine.class)) {
|
||||
|
||||
t.heading("1. managed invoice, getLines().clear(), merge(invoice), flush()");
|
||||
Long id1 = invoice(db, "M-1", 2);
|
||||
Throwable e1 = run(t, "clear(); merge(inv); flush()", () -> db.txv(s -> {
|
||||
Invoice inv = s.find(Invoice.class, id1);
|
||||
inv.getLines().clear();
|
||||
s.merge(inv);
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows: InvoiceLine=" + db.count("InvoiceLine"));
|
||||
|
||||
t.heading("2. managed invoice, clear(), add one new line, merge(invoice), flush()");
|
||||
long before = db.count("InvoiceLine");
|
||||
Long id2 = invoice(db, "M-2", 2);
|
||||
Throwable e2 = run(t, "clear(); addLine(); merge(inv); flush()", () -> db.txv(s -> {
|
||||
Invoice inv = s.find(Invoice.class, id2);
|
||||
inv.getLines().clear();
|
||||
inv.addLine("replacement");
|
||||
s.merge(inv);
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows for invoice M-2 lines: " + db.rows("select description from InvoiceLine where invoice_id = " + id2));
|
||||
|
||||
t.heading("3. the normal detached round trip: load, close session, remove a line, merge in a new session");
|
||||
Long id3 = invoice(db, "M-3", 3);
|
||||
Invoice detached = db.tx(s -> {
|
||||
Invoice inv = s.find(Invoice.class, id3);
|
||||
inv.getLines().size();
|
||||
return inv;
|
||||
});
|
||||
detached.getLines().remove(0);
|
||||
Throwable e3 = run(t, "merge(detachedInvoice); flush()", () -> db.txv(s -> {
|
||||
s.merge(detached);
|
||||
s.flush();
|
||||
}));
|
||||
t.line("raw rows for invoice M-3 lines: " + db.rows("select count(*) from InvoiceLine where invoice_id = " + id3));
|
||||
assertThat(e3).isNull();
|
||||
assertThat(db.rows("select count(*) from InvoiceLine where invoice_id = " + id3)).containsExactly("2");
|
||||
t.line("outcomes: 1=" + (e1 == null ? "ok" : "threw") + " 2=" + (e2 == null ? "ok" : "threw") + " 3=" + (e3 == null ? "ok" : "threw"));
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Two entities with no cascade between them are removed in the "wrong" order. Hibernate 8's graph-based flush is meant to plan deletes from the foreign keys. */
|
||||
class T08_DeleteOrderTest {
|
||||
|
||||
private static String scenario(Map<String, String> settings, Transcript t, boolean mandatory) {
|
||||
AtomicReference<Throwable> thrown = new AtomicReference<>();
|
||||
AtomicReference<java.util.List<String>> sqlRef = new AtomicReference<>(java.util.List.of());
|
||||
try (Db db = Db.open(settings, AppUser.class, ProjectGood.class, Board.class, Card.class)) {
|
||||
Long[] ids = db.tx(s -> {
|
||||
if (mandatory) {
|
||||
Board b = new Board("order-test");
|
||||
s.persist(b);
|
||||
Card c = new Card("c", b);
|
||||
s.persist(c);
|
||||
return new Long[] {b.getId(), c.getId()};
|
||||
}
|
||||
AppUser u = new AppUser("order-test");
|
||||
s.persist(u);
|
||||
ProjectGood p = new ProjectGood("p", u);
|
||||
s.persist(p);
|
||||
return new Long[] {u.getId(), p.getId()};
|
||||
});
|
||||
var sql = Db.sql(() -> {
|
||||
try {
|
||||
db.txv(s -> {
|
||||
Object parent = mandatory ? s.find(Board.class, ids[0]) : s.find(AppUser.class, ids[0]);
|
||||
Object child = mandatory ? s.find(Card.class, ids[1]) : s.find(ProjectGood.class, ids[1]);
|
||||
s.remove(parent); // parent first ...
|
||||
s.remove(child); // ... then the child that still points at it
|
||||
s.flush();
|
||||
});
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
thrown.set(e);
|
||||
}
|
||||
});
|
||||
sqlRef.set(sql);
|
||||
t.step("remove(parent); remove(child); flush()", sql);
|
||||
if (thrown.get() != null) {
|
||||
t.line(" threw: " + Db.chain(thrown.get()));
|
||||
t.line(" cause: " + Db.firstLine(Db.root(thrown.get())));
|
||||
}
|
||||
t.line("raw rows: parent=" + db.count(mandatory ? "Board" : "AppUser") + " child=" + db.count(mandatory ? "Card" : "ProjectGood"));
|
||||
}
|
||||
String firstDelete = sqlRef.get().stream().filter(x -> x.startsWith("delete from ")).findFirst().map(x -> x.split(" ")[2]).orElse("none");
|
||||
return (thrown.get() == null ? "ok" : "threw") + "/first delete: " + firstDelete;
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteOrder() {
|
||||
Transcript t = new Transcript("08-delete-order", "Deleting a parent and its (non-cascaded) child in one flush, parent removed first");
|
||||
String[] out = new String[4];
|
||||
int i = 0;
|
||||
for (boolean mandatory : new boolean[] {false, true}) {
|
||||
t.heading(mandatory ? "Card.board is optional = false (the foreign key cannot be nulled)" : "ProjectGood.owner is nullable");
|
||||
t.line("-- default settings");
|
||||
out[i++] = scenario(Map.of(), t, mandatory);
|
||||
t.line("-- hibernate.flush.queue.type=legacy (a setting Hibernate 8 introduced; ignored by 7.x)");
|
||||
out[i++] = scenario(Map.of("hibernate.flush.queue.type", "legacy"), t, mandatory);
|
||||
}
|
||||
t.line("");
|
||||
t.line("outcomes: nullable default=" + out[0] + " | nullable legacy=" + out[1] + " | mandatory default=" + out[2] + " | mandatory legacy=" + out[3]);
|
||||
t.write();
|
||||
boolean h7 = Transcript.LABEL.equals("h7");
|
||||
assertThat(out[0]).isEqualTo(h7 ? "ok/first delete: AppUser" : "ok/first delete: ProjectGood");
|
||||
assertThat(out[1]).isEqualTo("ok/first delete: AppUser");
|
||||
assertThat(out[2]).startsWith("threw");
|
||||
assertThat(out[3]).startsWith("threw");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Which JPA operation travels along which cascade type: five operations against seven one-to-one associations to the same Leaf entity. */
|
||||
class T09_CascadeMatrixTest {
|
||||
|
||||
static final List<String> FIELDS = List.of("onPersist", "onMerge", "onRemove", "onRefresh", "onDetach", "onAll", "none");
|
||||
|
||||
/** A probe whose only association is {@code field}, with the leaf already saved, and the ids of both. */
|
||||
private static Long[] saved(Db db, String field) {
|
||||
return db.tx(s -> {
|
||||
Leaf leaf = new Leaf("original");
|
||||
s.persist(leaf);
|
||||
Probe p = new Probe();
|
||||
p.set(field, leaf);
|
||||
s.persist(p);
|
||||
return new Long[] {p.getId(), leaf.getId()};
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean persistTravels(Db db, String field) {
|
||||
try {
|
||||
db.txv(s -> {
|
||||
Probe p = new Probe();
|
||||
p.set(field, new Leaf("new"));
|
||||
s.persist(p);
|
||||
s.flush();
|
||||
});
|
||||
return true;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean mergeTravels(Db db, String field) {
|
||||
Long[] ids = saved(db, field);
|
||||
Probe detached = db.tx(s -> s.find(Probe.class, ids[0]));
|
||||
detached.get(field).setLabel("changed in detached copy");
|
||||
db.txv(s -> {
|
||||
s.merge(detached);
|
||||
s.flush();
|
||||
});
|
||||
return db.rows("select label from Leaf where id = " + ids[1]).get(0).equals("changed in detached copy");
|
||||
}
|
||||
|
||||
private static boolean removeTravels(Db db, String field) {
|
||||
Long[] ids = saved(db, field);
|
||||
try {
|
||||
db.txv(s -> {
|
||||
s.remove(s.find(Probe.class, ids[0]));
|
||||
s.flush();
|
||||
});
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
return db.rows("select count(*) from Leaf where id = " + ids[1]).get(0).equals("0");
|
||||
}
|
||||
|
||||
private static boolean refreshTravels(Db db, String field) {
|
||||
Long[] ids = saved(db, field);
|
||||
return db.tx(s -> {
|
||||
Probe p = s.find(Probe.class, ids[0]);
|
||||
Leaf leaf = p.get(field);
|
||||
s.doWork(cn -> {
|
||||
try (var st = cn.createStatement()) {
|
||||
st.execute("update Leaf set label = 'changed in the database' where id = " + ids[1]);
|
||||
}
|
||||
});
|
||||
s.refresh(p);
|
||||
return leaf.getLabel().equals("changed in the database");
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean detachTravels(Db db, String field) {
|
||||
Long[] ids = saved(db, field);
|
||||
return db.tx(s -> {
|
||||
Probe p = s.find(Probe.class, ids[0]);
|
||||
Leaf leaf = p.get(field);
|
||||
s.detach(p);
|
||||
return !s.contains(leaf);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void matrix() {
|
||||
Transcript t = new Transcript("09-cascade-matrix", "Which operation propagates along which cascade type (one @OneToOne per type, all to Leaf)");
|
||||
try (Db db = Db.open(Probe.class, Leaf.class)) {
|
||||
String[] ops = {"persist", "merge", "remove", "refresh", "detach"};
|
||||
List<List<String>> travelled = new ArrayList<>();
|
||||
for (String op : ops) {
|
||||
List<String> hit = new ArrayList<>();
|
||||
for (String f : FIELDS) {
|
||||
boolean yes = switch (op) {
|
||||
case "persist" -> persistTravels(db, f);
|
||||
case "merge" -> mergeTravels(db, f);
|
||||
case "remove" -> removeTravels(db, f);
|
||||
case "refresh" -> refreshTravels(db, f);
|
||||
default -> detachTravels(db, f);
|
||||
};
|
||||
if (yes) {
|
||||
hit.add(f);
|
||||
}
|
||||
}
|
||||
travelled.add(hit);
|
||||
t.line(String.format("%-8s propagates along: %s", op + "()", hit));
|
||||
}
|
||||
t.write();
|
||||
assertThat(travelled.get(0)).containsExactly("onPersist", "onAll");
|
||||
assertThat(travelled.get(1)).containsExactly("onMerge", "onAll");
|
||||
assertThat(travelled.get(2)).containsExactly("onRemove", "onAll");
|
||||
assertThat(travelled.get(3)).containsExactly("onRefresh", "onAll");
|
||||
assertThat(travelled.get(4)).containsExactly("onDetach", "onAll");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ankurm.cascade;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Collects what a test observed and writes output/NN-name-<label>.txt (label = h7 or h8); the tests assert the same facts. */
|
||||
final class Transcript {
|
||||
|
||||
static final String LABEL = System.getProperty("h.label", "h7");
|
||||
static final String VERSION = System.getProperty("h.version", "?");
|
||||
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
private final Path file;
|
||||
|
||||
Transcript(String name, String title) {
|
||||
this.file = Path.of("output", name + "-" + LABEL + ".txt");
|
||||
line("# " + title);
|
||||
line("# Hibernate ORM " + VERSION + ", H2, JDK " + Runtime.version().feature());
|
||||
}
|
||||
|
||||
Transcript line(String s) {
|
||||
lines.add(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
Transcript heading(String s) {
|
||||
line("");
|
||||
return line("== " + s);
|
||||
}
|
||||
|
||||
/** A step: the label, then every SQL statement Hibernate prepared during it. */
|
||||
Transcript step(String label, List<String> sql) {
|
||||
line("-- " + label);
|
||||
if (sql.isEmpty()) {
|
||||
line(" (no SQL)");
|
||||
}
|
||||
for (String s : sql) {
|
||||
line(" sql> " + s);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
void write() {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, lines);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user