Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

java - Create and populate child table from Parent table using Hibernate Annotation

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???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...