简体   繁体   中英

Spring Boot: How to create similar another entity by using existing entity class

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;
}

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

You can use inhertiance with @MappedSuperclass. But if I will design this application I will add boolean field "active" to Employee class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM