Search code examples
jpaeclipselink

eclipselink 2 OneToMany with one association table how to delete from one side


i have the following entity relationship: SideA:

@Entity
@Table(name = "SideA")
    public class SideA {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long  id;

    @CascadeOnDelete
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sideA", cascade=CascadeType.ALL)
    private List<ABAssociation> association = new ArrayList<ABAssociation>();
}

Side B:

@Entity
@Table(name = "SideB")
public class SideB {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long  id;

    @CascadeOnDelete
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sideB", cascade=CascadeType.ALL)
    private List<ABAssociation> association = new ArrayList<ABAssociation>();
}

ABAssociation:

@Entity
@Table(name = "ABAssociation")
public class ABAssociation {

   @EmbeddedId
   private ABAssociationPK pk = new ABAssociationPK();
   @ManyToOne(cascade=CascadeType.MERGE)
   @MapsId("aId")
   private SideA sideA;

   @ManyToOne(cascade=CascadeType.MERGE)
   @MapsId("bId")
   private SideB sideB;
}

ABAssociationPK:

@Embeddable
public class ABAssociationPK implements java.io.Serializable{
    private long aId;
    private long bId;
}

my problem is when i delete one side, the database delete the row in ABAssociation , but still stay in cache.

test code is like the follow:

SideA a = new SideA();
SideB b = new SideB();
entitymanager.persist(a);
entitymanager.persist(b);

ABAssociation ab = new ABAssociation()
ab.setSideA(a);
ab.setSideB(b);
entitymanager.persist(ab);

a.getABAssociationList().add(ab);
b.getABAssociationList().add(ab);

a = entitymanager.merge(a);
b = entitymanager.merge(b);

entitymanager.delete(a);

Since "a" was deleted, the relationship between "a" and "b" should be deleted too. but when i check the "b.getABAssociationList().size()" it still there, even there is no rows in ABAssociation table in DB.

it this related to the share cache issue ?


Solution

  • In JPA you must maintain you object's relationships.

    If you remove an object, you must first remove all references to it.

    See, http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Object_corruption.2C_one_side_of_the_relationship_is_not_updated_after_updating_the_other_side