繁体   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