I got the @PrimaryKeyJoinColumn working before , now I'm trying with spring boot and I can't figure what I'm missing , it's very weird as it seems I have done everything right :
Person class :
@Table(name = "PERSON")
@Entity
@Getter
@Setter
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "NAME")
private String name;
@OneToOne(cascade = CascadeType.PERSIST)
@PrimaryKeyJoinColumn
private Department department;
}
Department class :
@Table(name = "DEPARTMENT")
@Entity
@Getter
@Setter
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "NAME")
private String name;
@OneToOne(mappedBy = "department")
private Person person;
}
The service class :
@Transactional
public void addPerson() {
Person person = new Person();
person.setName("person 1");
Department department = new Department();
department.setName("test");
department.setPerson(person);
person.setDepartment(department);
personRepository.save(person);
}
That's what I get in the DB : Person table :
ID Name
13 person 1
Department table :
ID Name
18 test
Desired output : both ID should be identical ( Person ID should be 18 not 13) any idea ?
Update: hibernate always tries to insert Person without an ID , so if I remove auto increment from Person ID and tries to insert the person with existing department I get :
Hibernate: insert into person (name) values (?)
Field 'id' doesn't have a default value
Update 2: it seems the @PrimaryKeyJoinColumn won't handle the ID generation to be as the department class, so I need to use generator. I wonder because the same annotation works in Inheritance joined without doing anything on the ID of subclass. So I'm expecting an answer explaining why ID generation works in Inheritance joined , while OneToOne needs a generator