2010-02-23 71 views
0

在我的春天/ OpenJPA的基於應用程序中,我有兩個簡單的實體:JPA合併問題

@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()始終爲空,事件如果我在這裏設置空的hashmap。 :/爲什麼

+0

我認爲這將有助於如果你可以顯示調用'createEntity'的代碼。特別是,如果你能夠證明當你構造你的遊戲對象時,你會有一條線,比如'games = new ArrayList ();' – John 2010-02-23 12:03:32

+0

其中是標題的「合併」嗎? – Bozho 2010-02-23 13:05:56

回答

1

我建議有:

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

因此默認值將是一個空的集合(好習慣),而不是null(糟糕的做法)

+0

事實上,支持merge()(至少在OpenJPA上)是非常重要的,如果初始值設置爲NULL,那麼你不能在merge() – comeGetSome 2015-01-07 11:36:27