[英]Save an entity and all its related entities in a single save in spring boot
[英]Save an entity and it's related entity in one save in spring boot
我有一個實體Period
:
@Entity
@Table(name = "period")
public class Period implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "day_of_week")
private DayOfWeek dayOfWeek;
@Column(name = "start_time")
private LocalTime startTime;
@Column(name = "end_time")
private LocalTime endTime;
@JsonIgnoreProperties(value = { "period" }, allowSetters = true)
@OneToOne
@JoinColumn(unique = true)
private Periodicity periodicity;
及其相關實體Periodicity
:
@Entity
@Table(name = "periodicity")
public class Periodicity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "periodicity_label")
private TypeOfPeriodicity periodicityLabel;
@Column(name = "end_time")
private LocalTime endTime;
@JsonIgnoreProperties(value = { "periodicity", "resource" }, allowSetters = true)
@OneToOne(mappedBy = "periodicity")
private Period period;
也是一個枚舉TypeOfPeriodicity
:
public enum TypeOfPeriodicity {
JOURNALIER,
HEBDOMADAIRE,
MENSUEL,
SEMESTRIEL,
TRIMESTRIEL,
ANNUEL,
}
在創建新期間的字體末尾,我指定該期間的 TypeOfPeriodicity。 在后端,我想從 Period 中獲取 TypeOfPeriodicity 和 endTime ,同時使用這些屬性保存一個新的 Periodicity 。 知道怎么做嗎? 我需要幫助。
在 period 類中,您可以使用@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
在保存 Period 實體時使休眠保持 Periodicity 實體。 有關 CascadeType 類型的作用的更多信息,請參閱https://www.baeldung.com/jpa-cascade-types ,但通常使用 ALL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.