Xiwen
Xiwen

Reputation: 263

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 ?

Upvotes: 0

Views: 1940

Answers (3)

F&#225;bio Almeida
F&#225;bio Almeida

Reputation: 296

you can force update your list using evict() like this:

getEntityManager().getEntityManagerFactory().getCache().evict(ABAssociation.class);

Upvotes: 0

Chris
Chris

Reputation: 21165

somewhat, yes. You need to remove B's reference to ABAssociation when ABAssociation gets deleted to maintain the cache with what is in the database. You might do this by using a preremove event on ABAssociation if you cannot do it in your application.

Upvotes: 2

James
James

Reputation: 18379

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

Upvotes: 2

Related Questions