-1

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

saptarshi
  • 97
  • 1
  • 14
  • Your question is not very clear. Hibernate is not used to create tables. Hibernate is used to access tables. What don't you understand in http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-manytoone ? Also, note that adding a remark column in the employee table would be much easier. – JB Nizet May 28 '12 at 12:50

1 Answers1

0

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.

d1e
  • 6,372
  • 2
  • 28
  • 41
  • If I'm not mistaken, modifying the remark of an existing, attached employee would cause an exception. The EmployeeRemark entity must be persisted somehow. – JB Nizet May 28 '12 at 13:10
  • Hmm, I thought of it, but wasn't sure. Maybe modifying current Remark will be a better solution? – d1e May 28 '12 at 13:13
  • Even that would not be sufficient, unless a remark is systematically created as soon as an employee is created (i.e. the constructor of Employee should initialize its remark). – JB Nizet May 28 '12 at 13:14
  • Thanks for the reply...but the issue is the type of employeeRemark have to keep String as it is specified in the schema. Can I do it keeping the employeeRemark as String type? – saptarshi May 28 '12 at 13:56