Create and populate child table from Parent table using Hibernate Annotation

瘦欲@ 提交于 2019-12-13 08:29:14

问题


I need to create a table EMPLOYEE_REMARK from a table EMPLOYEE. And need to do it with Annotation Hibernate.

EMPLOYEE

EMP_ID, EMP_FNAME, EMP_LNAME

EMPLOYEE_REMARK

EMP_REMARK_ID, EMP_ID, REMARK

it will be a OnetoOne relationship i.e, for each EMP_ID there will be one REMARK. REMARK could be null.

please help me with the solution... Can it be done by creating one class from employee and populate the EMPLOYEE_REMARK from it???


回答1:


Basically here is the way of doing what you want.

Employee

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {

    @Id
    @Column(name = "EMP_ID")
    private Long id;
    @Column(name = "EMP_FNAME")
    private String firstName;
    @Column(name = "EMP_LNAME")
    private String lastName;
    @OneToOne(mappedBy = "employee", cascade = CascadeType.ALL,
    orphanRemoval = true)
    private EmployeeRemark employeeRemark;

    public void setRemark(String remark) {
        this.employeeRemark = new EmployeeRemark();
        this.employeeRemark.setRemark(remark);
        this.employeeRemark.setEmployee(this);
    }

    public String getRemark() {
        return employeeRemark == null ? null : employeeRemark.getRemark();
    }

    //getters and setters
}

Employee Remark

@Entity
@Table(name = "EMPLOYEE_REMARK")
public class EmployeeRemark implements Serializable {

    @Id
    @Column(name = "EMP_REMARK_ID")
    private Long id;
    @OneToOne
    @JoinColumn(name = "EMP_ID")
    private Employee employee;
    @Column(name = "REMARK")
    private String remark;

    //getters and setters
}

When saving employee, just call save on employee. EmployeeRemark will cascade to all operations and will be removed along with employee or if it become an orphan in other way.



来源:https://stackoverflow.com/questions/10784891/create-and-populate-child-table-from-parent-table-using-hibernate-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!