While trying to enhance my application I came across this issue with removing entities with
unidirectional OneToMany relationship.
Tables used (I use potgres):
create table a (id varchar(10), aname varchar(10), primary key(id));
create table b (id serial, bname varchar(10), primary key(id));
and join table:
create table a_b(id serial, aid varchar(10), bid int, primary key(id), foreign key(aid) references a(id),
foreign key (bid) references b(id));
Entity A among all setter/getters and required field has the following:
@JoinTable(name = "a_b"
private java.util.List<B> bCollection;
Entity B does have only getters/setters and no relationship fields defined (relationship is unidirectional).
In session facade I create new A entity and add 2 B entities to bCollection, merging A and all records in
a, a_b and b tables are created fine.
Now in the same session bean I do:
A c2 = findByPK(Contact.class, "TEST");
c2 = em.merge(c2);
Last line removes database rows in table a and a_b fine. Table b entries are not removed.
If I add in entity A the following:
Then, when doing em.remove(c2) I get the following exception:
org.postgresql.util.PSQLException: ERROR: update or delete on "b" violates foreign key constraint
"a_b_bid_fkey" on "a_b"
Detail: Key (id)=(10) is still referenced from table "a_b".
So now it tries to remove also records in table b first and fails, because a_b still contains references to
Is that an expected behaviour ?