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

别说谁变了你拦得住时间么 提交于 2019-12-11 20:40:13

问题


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 ?


回答1:


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




回答2:


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.




回答3:


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

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


来源:https://stackoverflow.com/questions/10804975/eclipselink-2-onetomany-with-one-association-table-how-to-delete-from-one-side

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!