我認爲這是@ManyToOne和@OneToMany註釋會爲你工作。如果您將保存將(必須)包含目標列表的對象匹配,則每個目標都將通過匹配進行保存。
Match.java
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "match")
public class Match {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
@JsonBackReference
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "goal", joinColumns = {
@JoinColumn(name = "match_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "goal_id",
nullable = false, updatable = false) })
protected List<Goal> goals;
}
Goal.java
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "goal")
public class Goal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "match", joinColumns = {
@JoinColumn(name = "goal_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "match_id",
nullable = false, updatable = false) })
protected Match matche;
}
謝謝!一個目標不能成爲許多比賽的一部分。它只是一個Match的一部分。目標是多對一。即使我要拯救Goal,我也不想保存比賽,我只想檢查比賽是否存在。如果它不存在,那麼它也將保存匹配。請根據此評論更新您的答案。 –
感謝您的更新。但是在Match類中,它應該是OneToMany。請相應更新。 –
這適合你嗎? – Pras