I have @OneToOne
bidirectional relationship where parent (P
) class has:
@OneToOne(optional = true, mappedBy = "owner", orphanRemoval = true)
@Cascade({org.hibernate.annotations.CascadeType.ALL})
on getter and child class (C
) has on getter:
@ForeignKey(name = "fk_reference_owner")
@MapsId("owner")
@ManyToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumns({
@PrimaryKeyJoinColumn(name = "owner_oid", referencedColumnName = "oid"),
@PrimaryKeyJoinColumn(name = "owner_id", referencedColumnName = "id")
})
Abbreviations:
P(<it's primary key>)
C(<it's primary key, and it's also FK to P>, <another PK>)
Situation looks like this:
I have P(1)
and C(1, a)
persisted in database - and C(1, a)
is owned by P(1)
. Now somewhere in code I create detached instances of P(1)
and C(1, a)
. When I call session.merge(p)
then all properties are merged and after session.commit()
they are updated. But when I change C(1, a)
on detached object to for example C(1, b)
then C(1, a)
is not deleted, only C(1, b)
is persisted. I know it's because that C(1, b)
doesn't exist in database and hibernate didn't get clear instruction to delete C(1, a)
- but it should be probably automatic because of @OneToOne
. Later it fails because of broken @OneToOne
relationship. I know one of possible solutions is set P.setC(null)
on attached object. But it's not possible in my case. In time of merging I already have "updated" detached object P
.
Can I set child to null somewhere during merging with use of custom tuplizer or something like that?
Do you have any ideas how this could be done?