Composite foreign key lost in merge () operation (JPA / Hibernate)

Imagine an object Employeethat is referenced Departmentusing a complex key :

@Entity
public class Employee {
   ...
   @ManyToOne
   @JoinColumns({
      @JoinColumn(name="dept_country", referencedColumnName="country"),
      @JoinColumn(name="dept_id", referencedColumnName="id")
   })
   private Department dept;
   ...

In a non-Bean session, I associate an employee with the department by setting the appropriate attribute:

employee.setAbc(abc);
System.out.println(entityManager.contains(aDepartment)));  //true
employee.setDepartment(aDepartment);
employee.setXyz(xyz);
entityManager.merge(employee);

=> All attributes are correctly saved (updated) in the database, except for the Department .

I wonder if this is due to the composite key, because when I look at Hibernate SQL in the background, exactly such foreign key columns are missing.

14:46:18 INFO  [STDOUT#write] Hibernate:
14:46:18 INFO  [STDOUT#write]     update
14:46:18 INFO  [STDOUT#write]         employees
14:46:18 INFO  [STDOUT#write]     set
14:46:18 INFO  [STDOUT#write]         abc=?,
14:46:18 INFO  [STDOUT#write]         xyz=?,
14:46:18 INFO  [STDOUT#write]     where
14:46:18 INFO  [STDOUT#write]         id=?

Hope I missed something trivial ...

+3
source share
1 answer

Shoot!

, Employee/Department , . ! : updatable

, :

   @ManyToOne
   @JoinColumns({
      @JoinColumn(name="dept_country", referencedColumnName="country", insertable = false, updatable = false),
      @JoinColumn(name="dept_id", referencedColumnName="id", insertable = false, updatable = false)
   })

: updatable = true

!

P.S: , , , .

+2

Source: https://habr.com/ru/post/1764151/


All Articles