2010-01-13 82 views
2

我有两个实体:JPA父子删除

@Entity 
public class Game implements Serializable{ 

@ManyToOne 
@JoinColumn(name = "target_id") 
protected GameObject target; 
} 

@Entity 
public class GameObject implements Serializable { 

@OneToMany(mappedBy = "target", cascade = CascadeType.ALL) 
protected Collection<Game> games = new HashSet<Game>();  
} 

在一个交易我删除从游戏对象的游戏。

@Transactional 
public void deleteEntity(Object entity) { 
    getEntityManager().remove(entity); 
    getEntityManager().flush(); 
} 

之后,当我尝试加载gameObject时,它已删除集合中的游戏。此游戏只有id属性正确,其余为空。什么是错的,为什么这个游戏仍然在coolection?

回答

2

因为你有游戏游戏对象实体之间的双向关系。当您删除游戏,你切断关系,只有一面;要删除的游戏 - 在数据库>游戏对象的引用,但游戏对象 - >游戏引用保持。您的deleteEntity方法应该这样做:

public void deleteEntity(Game game) { 
    // WARNING - Untested code, only use as an example 
    GameObject gameObject = game.getGameObject(); 
    gameObject.removeFromCollection(game); 
    getEntityManager().remove(game); 
    getEntityManager().merge(gameObject); 
} 

您的底层数据库可能支持外键约束。这意味着,当你的JPA实现试图从数据库中删除的游戏记录,该游戏对象的表有在游戏桌上外键约束不会允许记录被删除,但它允许归零您的所有列值(除了当然的主键/ ID)。