簡體   English   中英

在 JPA 一對多關系中分配給 NULL 的外鍵

[英]Foreign key assigned to NULL in JPA one-to-many relationship

我有以下一對實體類:

@Entity(name="metadata")
public class Metadata {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    // Note: Hibernate CascadeType.ALL is also being used elsewhere in this class, hence
    //       the fully qualified class name used below
    @OneToMany(cascade = javax.persistence.CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "metadata")
    private List<Attachment> attachments;

    // getters and setters
}

@Entity(name="attachment")
public class Attachment {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "metadata_id", referencedColumnName = "id", nullable = false, updatable = false)
    private Metadata metadata;

    // getters and setters
}

為了完整起見,這是我構建Metadata object 的方式:

Metadata metadata = modelMapper.map(req, Metadata.class);
List<Attachment> attachments = new ArrayList<>();
// the files come as a parameter to a Spring controller endpoint (FYI)
for (MultipartFile file : files) {
    Attachment attachment = new Attachment();
    attachment.setContents(file.getBytes());
    attachment.setFilename(file.getOriginalFilename());
    attachments.add(attachment);
}
metadata.setAttachments(attachments);
metadata.setDraft(isDraft);

myJPARepository.save(metadata);

我在創建Metadata實體然后從我的 JPA 存儲庫調用save()時觀察到的是所有數據都正確寫入了我的數據庫(Postgres)。 但是,連接列metadata_id始終為NULL 起初,我認為這可能是由於未設置referencedColumnName屬性(其默認值為"" )引起的。 但是,如您在上面看到的那樣添加它確實解決了這個問題。

有誰知道為什么連接列metadata_id在數據庫表中總是顯示為NULL

您需要同步兩個 object,到目前為止,您正在創建元數據 object 並向其添加附件,並且您有級聯,以便將兩個實體保存到各自的表中。

但是,由於您具有雙向關系,因此您只在此處同步關系的一側,您需要為每個附件 object 設置相同的元數據 object ,然后 hibernate 才能鏈接外鍵。

我建議在元數據 object 上使用類似這樣的添加 function 而不是 setter

public void addAttachment(Attachment attachment) {
      attachments.add(attachment);
      attachment.setMetadata(this);
}

This way both the object would be in synch, use that inside in your for loop, you may have to initialise your collection inside metadata object before doing that or you can first check in above add function that if attachments list is null then create one and然后加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM