java - JPA cascade all causing integrity constraint -


i have 3 tables employee, boss, , address.

employee , boss in case share same address. when call entitymanager.remove on employee integrity constraint exception because tries delete address can't because boss still needs it. if no 1 using address though want removed. should annotations can delete orphans address avoid integrity constraint?

exception =

internal exception: java.sql.sqlintegrityconstraintviolationexception: delete on table 'employee' caused violation of foreign key constraint 'boss.... 

code =

public class employee { @onetomany(targetentity = address.class, orphanremoval = true,cascade = {     cascadetype.all  } fetch=fetchtype.eager) @jointable(name = "employee_address") @xmlelement(required = true) @ordercolumn protected list<address> addresses;  } public class boss {   @onetomany(targetentity = address.class, orphanremoval = true, cascade = {     cascadetype.all  }fetch=fetchtype.eager) @jointable(name = "boss_address") @xmlelement(required = true) @ordercolumn protected list<address> addresses; } 

address class knows nothing boss or employee.

your annotations correct. when deleting employee attempt remove it's addresses.

but if both uses same address removal fail.

given scenario use list of cascades options without casacadetype.delete or casacadetype.all , solve issue programatically.

also not use orphanremoval in this. see jpa 2.0 spec, section 2.9:

if entity target of relationship removed relationship (by setting relationship null or removing entity relationship collection), remove operation applied entity being orphaned. remove operation applied @ time of flush operation. orphanremoval functionality intended entities privately "owned" parent entity. portable applications must otherwise not depend upon specific order of removal, , must not reassign entity has been orphaned relationship or otherwise attempt persist it. if entity being orphaned detached, new, or removed entity, semantics of orphanremoval not apply.

if remove operation applied managed source entity, remove operation cascaded relationship target in accordance rules of section 3.2.3, (and hence not necessary specify cascade=remove relationship).


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -