我是 JDO 及其概念的新手。我之前使用过 ORMLite,这非常简单,我不知道在 JDO 中应该如何做我在 ORMLite 中所做的事情。我有 2 个实体,Broadcast
并且Movie
. 每个Broadcast
都有一个Movie
,一个Movie
可以有很多个Broadcasts
。广播的 id 不会生成,它是在持久化之前配置的。所以这就是我所做的:
@PersistenceCapable
public class Broadcast {
@PrimaryKey
private String id;
@Persistent
private Movie movie;
//More fields....
}
现在这是Movie
类(同样没有生成 id,它是在保存对象之前配置的):
@PersistenceCapable
public class Movie {
@PrimaryKey
private String id;
@Persistent(mappedBy = "movie")
private List<Broadcast> broadcasts;
//More fields....
}
现在,我有一个 servlet,它可以获取并保存数据库中的所有数据。首先,我获取所有的Broadcasts
, 对于每个Broadcast
的电影,我只知道标题和它的 ID,所以我Broadcast
用一个Movie
对象在其中保存一个事务(因为有两个对象被保存,所以这必须是原子的行动):
// Check if this broadcast already exist.
try {
mgr.getObjectById(Broadcast.class, brdcst.getId());
} catch (Exception e) {
if(e instanceof JDOObjectNotFoundException){
Transaction tx = null;
try{
tx = mgr.currentTransaction();
tx.begin();
mgr.makePersistent(brdcst);
tx.commit();
}
catch(Exception e1){
sLogger.log(Level.WARNING, e.getMessage());
}
finally{
if (tx.isActive()) {
tx.rollback();
}
mgr.flush();
}
}
else sLogger.log(Level.WARNING, e.getMessage());
}
然后,我正在获取电影的数据并保存它,使用相同的 ID,覆盖前一个对象(在没有引用该Broadcast
对象的其他线程中)。
try {
sLogger.log(Level.INFO, "Added the movie: " + movie);
mgr.makePersistent(movie);
} catch (Exception e) {
e.printStackTrace();
}
finally{
mgr.flush();
}
所以要明确一点,这就是 ORMLite 中发生的事情,也是我想在这里发生的事情。当我保存Broadcast
对象时,我正在向其中添加带有 ID 的电影,因此将来此 ID 将帮助他Movie
在数据库中获取对其的引用。
但是,每当我在数据库中查询广播并希望在其中找到对电影的引用时,我得到的都是 null 或者这个异常:
Field Broadcast.movie should be able to provide a reference to its parent but the entity does not have a parent. Did you perhaps try to establish an instance of Broadcast as the child of an instance of Movie after the child had already been persisted?
那么,我在这里做错了什么?