简体   繁体   中英

Hibernate unidirectional oneToMany FK 0 instead of true ID

I am struggeling now for days with hibernate and a oneToMany relation. I hope someone could help me out ...

I have 2 entites: a Version and a Change Log. A Version has a list of Change Logs.

Version Entity:

@Table(name="change_log_version")
@Entity
public class ChangeLogVersionEntity {
  ...
  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinColumn(name= "version_id")
  public List<ChangeLogEntity> changeLogEntities = new ArrayList<>();
  ...

Change Log Entity:

@Table(name="change_log")
@Entity
public class ChangeLogEntity {
  ...
  @Column(name="version_id")
  private long versionId;
  ...

Now i am able:

  1. to create a Version object
  2. create a change Log Object
  3. Create a List and annding the Change Log Object from 2. to the list
  4. Set the list with the object from 3. to the Version object
  5. call the save() method from my injected crud repo of version and saving the version object
  6. The version gets inserted into the version table and the change log gets inserted into the change log version with the FK to version.

Works fine so far only my FK wont get updated in the change Log object (See attachment)

While debuging the mentioned flow -> FK remains 0 even the IDS are correctly set .

I found a solution for my problem: In order to refer a version to a change log I am using the primary key of the version as the foreign key of the change log. My @oneToMany mapping works fine. My change log entity consist the fk also which caused my issues. The fk should not be part of the entity (child) which you want to refer by the owner class. After removing the fk every work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM