spring-data-jpa 如何在使用Spring JPA进行OneToOne插入时更新其他表

f4t66c6m  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(178)

我有两个使用OneToOne相关性链接的数据表,其中一端存在于数据库中。当我插入另一端时,我希望第一端的外部索引键数据行能够更新,让它知道相关性,而不需要手动更新。这可能吗?
这是我的简化示例,我使用@MappedSuperclass,因为我在大多数实体中都有一些共享字段,我在这里包括它只是为了防止它导致问题。
基本实体

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

抽象图像类

@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();
}

用户配置文件照片

@Entity
@Data
public class UserProfilePhoto extends Image {

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "userProfilePhoto")
    private Profile profile;

    @Override
    public UUID getTypeId() {
        return user.getId();
    }
}

配置文件

@Entity 
public class Profile extends Base {

    //defines some other fields

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn()
    private UserProfilePhoto profilePhoto;

}

我在寻找以下行为:
1.将UserProfilePhoto保存到图像表(带有配置文件ID)时,配置文件中相应的ImageId会更新
1.删除配置文件时,将从图像表中删除相应的UserProfilePhoto。
1.删除UserProfilePhoto后,配置文件将保留,但外键列将为空。
通过研究,我认为这是可能的,但这是一个得到正确的注解的问题。我已经尝试了不同的组合没有运气。我正在寻找的甚至可能吗?

sg3maiej

sg3maiej1#

JPA中的任何双向关系都是由mappedBy所指示的那一方独占控制的,因此您需要在代码中更新那一方,以使其持久化。
您可以通过调用setter中的另一端,或者首先编辑另一端来实现这一点。

相关问题