简体   繁体   English

使用 Spring JPA 插入 OneToOne 时如何更新其他表

[英]How to update other table when inserting with OneToOne using Spring JPA

I have two tables joined with a OneToOne relationship, one side exists in the database.我有两个表以 OneToOne 关系连接,一侧存在于数据库中。 When I insert the other side I want the first side's foreign key column to update so that it knows about the relationship without having to do it manually.当我插入另一侧时,我希望第一侧的外键列更新,以便它知道关系而不必手动执行。 Is this possible.这可能吗。

Here's my simplified example, I am using @MappedSuperclass because I have some shared fields in most of my Entities I included it here just in case it's causing an issue.这是我的简化示例,我使用的是@MappedSuperclass,因为我在大多数实体中都有一些共享字段,我将其包含在此处以防万一它引起问题。

The base entity基础实体

@MappedSuperclass
@Data
public abstract class BaseEntity {
    //defines some common fields I have in all my entities such Id
}

Abstract Image class抽象图像 class

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype", discriminatorType = DiscriminatorType.STRING)
@Data
public abstract class Image extends BaseEntity {

    //defines some other fields
    
    public abstract UUID getTypeId();
}

UserProfilePhoto用户资料照片

@Entity
@Data
public class UserProfilePhoto extends Image {

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "userProfilePhoto")
    private Profile profile;
    
    @Override
    public UUID getTypeId() {
        return user.getId();
    }
}

Profile轮廓

@Entity 
public class Profile extends Base {
    
    //defines some other fields
    
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn()
    private UserProfilePhoto profilePhoto;
    
}

I'm looking for the following behavior:我正在寻找以下行为:

  1. When UserProfilePhoto is saved to image table (with Profile ID) the corresponding ImageId is updated in Profile当 UserProfilePhoto 保存到图像表(带有配置文件 ID)时,相应的 ImageId 在配置文件中更新
  2. When Profile is Deleted the corresponding UserProfilePhoto is deleted from image table.当配置文件被删除时,相应的 UserProfilePhoto 将从图像表中删除。
  3. When UserProfilePhoto is deleted Profile remains but the foreign key column is nulled.删除 UserProfilePhoto 时,配置文件仍然存在,但外键列为空。

From researching this I think it's possible but it's a matter of getting the annotations correct.通过对此的研究,我认为这是可能的,但问题是要让注释正确。 I've tried different combinations with no luck.我尝试了不同的组合,但没有运气。 Is what I'm looking for even possible?我正在寻找的东西是否可能?

No, it is not possible the way you describe it.不,不可能像你描述的那样。 Any bidirectional relationship in JPA is controlled exclusively by the side indicated by mappedBy , so you need to update that side in your code, in order to have it persisted. JPA 中的任何双向关系仅由mappedBy指示的一侧控制,因此您需要在代码中更新该一侧,以使其持久化。

You can do that by invoking the other side in the setter, or by editing the other side in the first place.您可以通过在 setter 中调用另一方,或首先编辑另一方来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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