![](/img/trans.png)
[英]Spring Boot | Making another Entity class object in Entity class
[英]Spring Boot: How to create similar another entity by using existing entity class
我正在開發一個簡單的應用程序,其中我有一個實體 class class Employee。 現在我想從現有員工創建/復制名為 ActiveEmployees 的新類似實體。 我想添加功能,如果我點擊新的 api 端點 -> POST: http://locahost:8080/api/employee/active/john -> 因此,它應該將現有的員工 John Record 保存在新表 active_employees 中所有表數據。
@Entity
@Table(name="employee")
public class Employee{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotNull
private String firstNname;
@Column
@NotNull
private String lastNname;
@Column
@NotNull
private String department;
@JsonManagedReference
@OneToOne(fetch = FetchType.LAZY,
mappedBy = "employee",
cascade = CascadeType.ALL,
orphanRemoval = true)
ActiveEmployee activeEmployee;
... Constructor, getters and setters
}
@Entity
@Table(name="active_employees")
public class ActiveEmployees {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@JsonBackReference
@OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private Employee employee;
}
我認為您應該在 hibernate 中使用 inheritance 映射,而不是使用兩個具有相同字段的表。 有多種策略。 檢查並使用最適合您要求的。
在此處閱讀教程https://www.javatpoint.com/hibernate-inheritance-mapping-tutorial
您可以將繼承與 @MappedSuperclass 一起使用。 但是,如果我要設計這個應用程序,我會將 boolean 字段“活動”添加到員工 class。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.