I'm developing one simple app where where I have an one entity class class Employee. And now I want to create/copy new similar entity called ActiveEmployees from existing Employee. I want to add functionality that If I hit the new api endpoint ->POST: http://locahost:8080/api/employee/active/john -> So, it should save existing Employee John Record in the new table active_employees with the all Table data.
@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;
}
CodePudding user response:
I think you should use inheritance mapping in hibernate instead having two table with same fields. There are multiple strategies. Check and use best one which fits your requirement.
Read the tutorial here https://www.javatpoint.com/hibernate-inheritance-mapping-tutorial
CodePudding user response:
You can use inhertiance with @MappedSuperclass. But if I will design this application I will add boolean field "active" to Employee class.