Kerdos Media
Kerdos Media

Reputation: 180

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. 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.

The base entity

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

Abstract Image 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
  2. When Profile is Deleted the corresponding UserProfilePhoto is deleted from image table.
  3. When UserProfilePhoto is deleted Profile remains but the foreign key column is nulled.

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?

Upvotes: 0

Views: 1158

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81862

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.

You can do that by invoking the other side in the setter, or by editing the other side in the first place.

Upvotes: 1

Related Questions