简体   繁体   English

在 JPA 一对多关系中分配给 NULL 的外键

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

I have the following pair of entity classes:我有以下一对实体类:

@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
}

For completeness, here is how I am building the Metadata object:为了完整起见,这是我构建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);

What I observe when creating a Metadata entity and then calling save() from my JPA repository is that all data does get correctly written to my database (Postgres).我在创建Metadata实体然后从我的 JPA 存储库调用save()时观察到的是所有数据都正确写入了我的数据库(Postgres)。 However, the join column metadata_id is always NULL .但是,连接列metadata_id始终为NULL At first, I thought this might have been caused due to the referencedColumnName attribute not being set (whose default is "" ).起初,我认为这可能是由于未设置referencedColumnName属性(其默认值为"" )引起的。 However, adding this in as you see above did remedy the problem.但是,如您在上面看到的那样添加它确实解决了这个问题。

Does anyone know why the join column metadata_id is always appearing as NULL in the database table?有谁知道为什么连接列metadata_id在数据库表中总是显示为NULL

You need to synch both of your object, as of now you are creating metadata object and adding attachment to it and you have cascade so that will save both entities into their respective table.您需要同步两个 object,到目前为止,您正在创建元数据 object 并向其添加附件,并且您有级联,以便将两个实体保存到各自的表中。

But, since you have bidirectional relationship, you are only synching one side of relation ship here only, you need to set the same metadata object to each attachment object as well, then hibernate will be able to link the foreign key.但是,由于您具有双向关系,因此您只在此处同步关系的一侧,您需要为每个附件 object 设置相同的元数据 object ,然后 hibernate 才能链接外键。

Instead of setter I would suggest use a add function on metadata object something like this我建议在元数据 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 then add. 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