开发者

JPA merge problem

开发者 https://www.devze.com 2022-12-20 19:55 出处:网络
In my spring/openjpa based applica开发者_Go百科tion, I have two simple entities: @Entity public class Game {

In my spring/openjpa based applica开发者_Go百科tion, I have two simple entities:

@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;
...}

I'm trying to save game object with associated 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;
}

And I get NullPointerException in line: entity.getTarget().getGames() is always null, event if I set here empty hashmap. :/ Why


I'd advise having:

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

Thus the default value will be an empty collection (good practice), rather than null (bad practice)

0

精彩评论

暂无评论...
验证码 换一张
取 消