我有两个实体:
@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属性正确,rest为空。出什么问题了,为什么这个游戏还在冷却中?
发布于 2010-01-14 03:36:29
因为您在游戏和GameObject实体之间存在双向关系。当您移除游戏时,您仅切断了关系的一侧;您移除了数据库中的游戏-> GameObject引用,但保留了GameObject ->游戏引用。您的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之外)。
https://stackoverflow.com/questions/2057575
复制相似问题