问题
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