JPA合并问题

时间:2010-02-23 11:14:17

标签: java jpa

在我的基于spring / openjpa的应用程序中,我有两个简单的实体:

@Entity
public class Game {

@Id
@GeneratedValue
protected Long id;
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE})
@JoinColumn(name = "target_id")
protected GameObject target;
...}

@Entity
public class GameObject {

@Id
@GeneratedValue
protected Long id;
@Column
protected String name;
@OneToMany(mappedBy = "target", cascade = CascadeType.ALL)
protected Collection<Game> games;
...}

我正在尝试使用关联的targetObject保存游戏对象:

@PersistenceContext
protected EntityManager entityManager;  

@Override
@Transactional
public Game createEntity(Game entity) {
    getEntityManager().persist(entity);
    if (entity.getTarget() != null) {
        entity.getTarget().getGames().add(this);
    }
    getEntityManager().getEntityManager().flush();
    return entity;
}

我得到NullPointerException行:entity.getTarget()。getGames()总是null,如果我在这里设置空hashmap则为event。 :/为什么

1 个答案:

答案 0 :(得分:1)

我建议:

protected Collection<Game> games = new HashMap<Game>();

因此,默认值将是一个空集合(良好做法),而不是null(不良做法)