我從來沒有遇到過我想一次性拯救多個父母和一個孩子的案例。就我而言,我有兩個父物體和一個子物體。兩個父物體在子物體上有一個外鍵。
我有一個這樣的例子->
@Entity
@Table("parentA")
public class ParentA
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ID;
@OneToMany(cascade = CascadeType.ALL, mappedBy="parentA")
private List<Child> child;
// Getters and Setters and some methods
}
@Entity
@Table("ParentB")
public class ParentB
{
@Column("CODE")
private Long code;
@OneToMany(cascade = CascadeType.ALL, mappedBy="parentB")
private List<Child> child;
// Getters and Setters and some methods}
@Entity
@Table("Child")
public class Child
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column("ID")
private Long ID;
@Column("parentA_ID")
private Long parentAId;
@Column("code")
private String code;//from parentB
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID", referencedColumnName = "parentA_ID")
private ParentA parentA;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "code", referencedColumnName = "code")
private ParentB parentB;
// Getters and Setters and some methods}
uj5u.com熱心網友回復:
您只需將屬性添加cascade = CascadeType.PERSIST到Child欄位:
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinColumn
private ParentA parentA;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinColumn
private ParentB parentB;
// ...
}
public interface ChildRepository extends JpaRepository<Child, Integer> {
}
然后當你保存子物體時,父物體將被保存:
ChildRepository childRepo;
// ...
var child = new Child();
var parentA = new ParentA();
var parentB = new ParentB();
parentA.setChild(List.of(child));
parentB.setChild(List.of(child));
child.setParentA(parentA);
child.setParentB(parentB);
childRepo.save(child);
您可以看到單個save插入了所有三行:
DEBUG n.t.d.l.l.SLF4JQueryLoggingListener -
Name:dataSource, Connection:4, Time:52, Success:True
Type:Prepared, Batch:False, QuerySize:1, BatchSize:0
Query:["insert into parenta values ( )"]
Params:[()]
DEBUG n.t.d.l.l.SLF4JQueryLoggingListener -
Name:dataSource, Connection:4, Time:0, Success:True
Type:Prepared, Batch:False, QuerySize:1, BatchSize:0
Query:["insert into parentb values ( )"]
Params:[()]
DEBUG n.t.d.l.l.SLF4JQueryLoggingListener -
Name:dataSource, Connection:4, Time:0, Success:True
Type:Prepared, Batch:False, QuerySize:1, BatchSize:0
Query:["insert into child (parenta_id, parentb_id) values (?, ?)"]
Params:[(3,3)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/408632.html
標籤:
上一篇:Hibernate一對一雙向混淆
下一篇:如何修復無法延遲初始化集合
