pankiba
pankiba

Reputation: 255

JPA JoinColumns behaviour

class Employee {

   @EmbeddedId
   private EmployeeId id; // composite key with two fileds companyId and employeeNumber

   @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
   private List<Phone> phoneList;
}

class Phone {

  @EmbeddedId
  private PhoneId phoneId; // composite key with three fileds companyId , employeeNumber and phoneNumber

  @ManyToOne
  @JoinColumns({
        @JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, 
        updatable = false),
        @JoinColumn(name = "EMPLOYEE_NUMBER_NEW", referencedColumnName = "EMPLOYEE_NUMBER", 
        insertable = false, updatable = false)})
  private Employee employee;

}

In above example, Employee table gets generated with column employeeId, employeeNumber. And Phone table gets generated with employeeId, employeeNumber, phoneNumber, employee_nuber_new.

When I am creating employee object and phone object, at the end employeeId and employeeNumber values in Phone table gets populated from Employee object ( as part of FK ) but employee_number_new column still have "null" value. I want to updated employee_number_new column with employeeNumber from Employee table.

Tried lot of ways including JoinFormula and all but no success. Can anybody throw some light on this ?

Thanks...

Upvotes: 1

Views: 158

Answers (1)

saifulislampi
saifulislampi

Reputation: 136

The reason you are getting a null value in the Phone table because you are using insertable = false in your JoinColumn definition. If you could set this to true then your problem would be solved.

Hibernate doesn't support the mixing of insertable and non-insertable columns. So you have to make companyId insertable too. But that leads to the possibility of your primary key being changed in the Phone table which you don't want.

So, we are left with two options, if the EMPLOYEE_NUMBER is the same in both tables don't create the new column EMPLOYEE_NUMBER_NEW column and use EMPLOYEE_NUMBER.

But if EMPLOYEE_NUMBER is not the same in both tables then and you need to save the employee number from employee object, create another insertable column it can be COMPANY_ID_EMP and make updateable false. That way when you save a phone object both EMPLOYEE_NUMBER_NEW and COMPANY_ID_EMP will be saved. But in practice COMPANY_ID_EMP and COMPANY_ID will be the same value.

The following code worked for me

    @ManyToOne
    @JoinColumns({
            @JoinColumn(name = "companyIdEmp", referencedColumnName = "companyId",  updatable = false),
            @JoinColumn(name = "employeeNumberNew", referencedColumnName = "employeeNumber", updatable = false)})
    private Employee employee;

Upvotes: 1

Related Questions