Question

I have a model class named Photo, and several other classes, representing different types of photo sources. The Photo class must remain agnostic of its source class, therefore for now, I have represented the relation as unidirectional OneToOne one the side of the source:

@Entity
public class Photo extends Model {
    ...
}

@Entity public class InstagramPhoto extends PhotoSource {       
    @Id     
    public String id;   
}

@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class PhotoSource extends GenericModel {
    @OneToOne(cascade=CascadeType.REMOVE)
    public Photo photo;
}

If I delete an InstagramPhoto instance, its associated Photo instance also gets deleted. The opposite operation however, throws an exception. I cannot delete a Photo instance. It gives me the following error:

Referential integrity constraint violation: "FK9366567567B45F0BDBD6: PUBLIC.INSTAGRAMPHOTO FOREIGN KEY(PHOTO_ID) REFERENCES PUBLIC.PHOTOS(ID) (4)";

P.S. Although, I'd prefer not to relate the Photo to a PhotoSource, I tried that too, with another @OneToOne. Then, the code does not compile, saying that a mappedBy relation to PhotoSource.photo cannot be made.

What can I do?

Was it helpful?

Solution 2

I resolved it by exchanging @MappedSuperclass with @Entity in PhotoSource, and moving the id definition there

OTHER TIPS

You could change your Photo class to reflect the association with the PhotoSource class. Then you add the cascade option to Photo which will delete the related Photo as well.

something like:

@Entity
public class Photo extends Model {
    @OneToOne(cascade=CascadeType.REMOVE)
    public PhotoSource photoSource;
}

Please keep in mind that this needs to reflect your database model. If you don't want to relate Photo to PhotoSource, you probably need to delete the related rows manually.

You can also try cascade = CascadeType.ALL It take cares of save, delete, update, evict, lock, replicate, merge, persist in relation between child and parents. hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top