views:

317

answers:

1

I have two entities:

@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>();    
}

In one transaction i delete on of games from game object.

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

After that, when I tries to load gameObject, it has deleted game in collection. This game has only id property correct, rest is null. What is wrong, why this game is still in coolection?

+1  A: 

Because you have a bidirectional relationship between the Game and GameObject entities. When you remove the Game, you are severing only one side of the relationship; you are removing the Game -> GameObject reference in the database, but the GameObject -> Game reference remains. Your deleteEntity method should do something like this:

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);
}

Your underlying database probably supports foreign key constraints. This means that when your JPA implementation tries to remove the Game record from the database, the foreign key constraint that the GameObject's table has on the Game table won't allow the record to be deleted, but it would allow a nulling of all your column values (except for the primary key/id of course).

rcampbell
thx, good solution
nablik