【发布时间】:2013-03-09 14:49:48
【问题描述】:
我是 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?
那么,我在这里做错了什么?
【问题讨论】:
标签: java google-app-engine entity-relationship one-to-many jdo