#StackBounty: #java #mysql #spring-boot #jpa Spring JPA OneToOne FK as PK Cascade.Remove

Bounty: 50

I’ve got two tables, b and a:

  • they have a one-to-one bidirectional relationship
  • a has a foreign key to b that defines this relationship
  • this foreign key is also considered as a primary key for a, and a JPA @ID
  • I want a cascade removal that deletes the related b when a is deleted
  • in MySQL, a‘s b_id is NOT NULL

The problem is that when I delete my A object with JPA repository, I get a ConstraintViolationException on its foreign key.
I would expect that both a and b rows are deleted (cleverly starting with a‘s one).

How could I work around this knowing that I want to keep:

  • my DB schema the same
  • the cascade removal from a to b
  • the b id being the JPA @Id for a
  `dbid` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`dbid`),

  `b_id` int(11) NOT NULL,
  KEY `b_fk` (`b_id`),
  CONSTRAINT `b_fk` FOREIGN KEY (`b_id`) REFERENCES `b` (`dbid`),

@Table(name = "a")
public class A {

    @Column(name = "b_id")
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name="property", value="b"))
    private Integer bId;

    @OneToOne(cascade = CascadeType.REMOVE)
    private B b;
@Table(name = "b")
public class B {

    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "dbid")
    private Integer id;

    @OneToOne(mappedBy = "b")
    private A a;

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.