2013-04-09 180 views
4

编辑:修改问题以更好地反映问题。最初发布问题hereJPA:级联删除不删除子

我有一个父母(Context)和一个孩子(User)实体(ManyToOne关系)。在父级上级联'删除'不会删除子级。代码如下:

//Owning side - child 
@Entity 
public class User { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private int id; 
    @Column(name = DBColumns.USER_NAME) 
    private String name; 
    @ManyToOne 
    @JoinColumn(name = DBColumns.CONTEXT_ID) 
    private Context context; 
} 

//parent 
@Entity 
public class Context { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private int id; 
    @Column(name = DBColumns.CONTEXT_NAME) 
    private String name; 
    @OneToMany(mappedBy = "context", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) 
    private Set<User> users = new HashSet<User>(); 
} 

//usage 
Context sampleContext = new Context("sampleContext"); 
em.persist(sampleContext); 
User sampleUser = new User(sampleContext, "sampleUser"); 
em.persist(sampleUser); 
em.remove(sampleContext); //should remove user as well but throws foreign key dependency error 
+0

。如果指定orphanRemoval = true,则不需要添加CascadeType.REMOVE。 (参见JSR338,第2.9节) – 8hZWKA 2016-10-08 10:54:54

回答

3

我需要删除之前刷新实体:

em.refresh(sampleContext); 
em.remove(sampleContext); 

早些时候,实体被删除(sampleContext)不知道sampleUser与之相关联(可能是因为sampleContext正从高速缓存中取出)。在delete之前执行refresh可确保实体从数据库更新。顺便说一句,

0

不要将您的关系表映射为en实体。使用@ManyToMany而是让你的用户实体拥有关系。

编辑:

因此您的关联表的主键必须由外国键。

看到这个http://giannigar.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/

+0

我想保持它的独立性,以便在稍后的时间点,我可以使用字符串而不是直接实体来指定映射(以促进正则表达式)。例如,我想通过映射'user:role :: *:employee'来说“All'users'属于'employee'角色”。 – Neo 2013-04-10 05:36:20

+0

@Venkatesh:查看编辑 – Gab 2013-04-10 06:53:59

+0

感谢您的链接。这是信息。但是,我也遇到了ManyToOne关系的问题。编辑问题以使问题更清楚。 – Neo 2013-04-10 12:07:43

1

你调用remove()上sampleUser不sampleContext,和用户没有级联删除对语境,所以你应该只看到用户被删除。

如果在sampleContext上调用remove(),则还必须确保在创建用户时将用户添加到上下文的用户。你很可能只设置用户的conext。

+0

更正了错字。它必须是'remove(sampleContext)'。 – Neo 2013-04-12 07:11:37

+0

该解决方案有效。但是,没有必要手动将'User'添加到'Context'的用户。 JPA自己做。我只需要刷新'Context'然后将其删除(以便其用户现在可以从数据库更新) – Neo 2013-04-12 07:15:17