简体   繁体   中英

Why does JDO think this detached object is clean?

I am trying to learn JDO (and at the same time its GAE and Spring intricacies) by creating a small web app, and am having trouble getting updated domain objects to persist back to the database. I initially grab the entity from the DB and detach it so that I can show it to the user and allow them to change it. Once the user has made the changes and posts the form back to the app, I again grab the entity from the DB (detached), update its properties, and then call a pm.makePersistent() . The abbreviated code is as follows:

User Domain Object:

@PersistenceCapable(detachable="true")
public class User extends BaseEntity {
    @Persistent
    private String firstName = "";
    @Persistent
    private String middleInitial = "";
    @Persistent
    private String lastName = "";
}

DAO Read Method:

public User read(Key key) throws DataException {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    User pkg, detached = null;
    try {
        pkg = (User) pm.getObjectById(User.class, key);
        detached = pm.detachCopy(pkg);
        detached.setIsAlreadyInDB(true);
    }
    catch (Exception e) {           
        throw new DataException("An error occured trying to read the User object. Details:\n" + e.getMessage());
    }
    finally {
        pm.close();
    }
    return detached;
}

DAO Update Method:

private void update(User pkg) throws DataException {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Transaction tx = pm.currentTransaction();

    try { 
        tx.begin();         
        pm.makePersistent(pkg);
        tx.commit();
    }
    finally { 
        if (tx.isActive()) tx.rollback();
        pm.close();
    }
}

Now when I get down into the update method, I've proven to myself that I'm working with just the same object from my read via inspecting its hashCode() , I've changed a value using the domain object's setter method, I've even printed the changed value to the console to make sure it's getting done, and JDOHelper.isDirty() still returns false, and therefore none of the changes get persisted back to the database. Any thoughts on what I'm missing or if I'm approaching this from the wrong angle? Thank you for helping out a JDO beginner!

JDOHelper.isDirty is for managed objects. A detached object is not managed. DataNucleus provides a helper method of its own to get the dirty fields while detached since the logic is implementation-specific String[] dirtyFieldNames = NucleusJDOHelper.getDetachedObjectDirtyFields(obj, pm);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM