Issue
I've got two tables, b
and a
:
- they have a one-to-one bidirectional relationship
a
has a foreign key tob
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
whena
is deleted - in MySQL,
a
'sb_id
isNOT 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
tob
- the
b
id being the JPA@Id
fora
CREATE TABLE `b` (
`dbid` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`dbid`),
);
CREATE TABLE `a` (
`b_id` int(11) NOT NULL,
KEY `b_fk` (`b_id`),
CONSTRAINT `b_fk` FOREIGN KEY (`b_id`) REFERENCES `b` (`dbid`),
);
@Entity
@Table(name = "a")
public class A {
@Id
@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)
@PrimaryKeyJoinColumn
private B b;
}
@Entity
@Table(name = "b")
public class B {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "dbid")
private Integer id;
@OneToOne(mappedBy = "b")
private A a;
}
[EDIT] After all discussions in answer comments and re-reading my question, the proposals with orphanRemoval
indeed are in scope and work.
Solution
If you want to delete object of B
, whenever the associated A
is deleted (it's the fourt point of your wishlist:
I want a cascade removal that deletes the related
b
whena
is deleted
then you need to change your mapping in A
to:
@OneToOne(cascade = CascadeType.REMOVE, orphanRemoval = true)
@PrimaryKeyJoinColumn
private B b;
Answered By - Andronicus