1

我正在使用 JDO 嵌入式实体。我已经通过本教程很好地设置了父实体和子实体。我的问题是我似乎无法让我对子实体所做的更改持续存在。这是我的两门课:

家长:

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class TestEntity {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private String name;

    @Persistent
    @Embedded
    private TestEntitySub sub;

    public TestEntitySub getSub() {
        return sub;
    }

    public void setSub(TestEntitySub sub) {
        this.sub = sub;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

孩子:

@PersistenceCapable
@EmbeddedOnly
public class TestEntitySub {
    @Persistent
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
}

修改代码:

PersistenceManager pm = PMF.get().getPersistenceManager();
TestEntity test = pm.getObjectById(TestEntity.class, 75L); //object has id=75
test.getSub().setState("New State");    
pm.makePersistent(test);
pm.close();

代码运行没有错误,但数据存储显示没有变化。我尝试了各种组合,包括持久化子对象、在父对象中重置子对象的字段等,但均无效。如果我修改父母的name而不是孩子的state,它就可以了。那么如何修改孩子的字段呢?

4

1 回答 1

1

I'd still love a more legitimate answer, but for anyone else struggling with this, I did find a workaround:

PersistenceManager pm = PMF.get().getPersistenceManager();
TestEntity test = pm.getObjectById(TestEntity.class, 75L); //object has id=75
TestEntitySub sub = test.getSub();  //Get the embedded entity
sub = pm.detachCopy(sub);           //Make a detached copy
sub.setState("New State");          //Update it
test.setSub(sub);                   //set it as the new embedded entity
pm.makePersistent(test);            //and persist the parent
pm.close();

The downside is that the PM has to make a complete copy of your embedded object. I'm assuming there's a better way, so if you know one, please share.

于 2013-04-15T16:57:52.077 回答