0

I have a problem using GAEJ and JDO for storing the data. This is what I'm working with:

class Usuari.java:

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;

@Persistent
private String email;

@Persistent
private String rol="";

class DBUtils.java: I've tried with two ways of doing the delete operation:

// This method removes a record from the database using its unique Key
public static boolean eliminar(Key k) throws Exception {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    String kind;
    Long id;
    kind = k.getKind();
    id = k.getId();
    try {
        if (k.getKind().equals("Usuari")) {
            Usuari u = (Usuari)pm.getObjectById(k);
            pm.deletePersistent(u);
            _log.log(Level.INFO, "Deleted an entity->kind: " + kind + " id: " + id);
        }

        return true;
    } catch (Exception e) {
        _log.log(Level.SEVERE, "Unable to delete an entity->kind: " + kind + " id: " + id);
        System.err.println(e.getMessage());
        throw e;
    }
    finally {
        pm.close();
    }
}

// This method removes a record from the database using its unique Key - too
public static void eliminar2(Key k) throws Exception {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    javax.jdo.Transaction tx = pm.currentTransaction();
    try
    {
        tx.begin();
        if (k.getKind().equals("Usuari")) {
            Usuari u = (Usuari) pm.getObjectById(k);
            pm.deletePersistent(u);
        }
        tx.commit();
    }
    catch (Exception e)
    {
        if (tx.isActive())
        {
            tx.rollback();
        }
        throw e;
    }
}

I'm able to create new instances of some class "Usuari" but I can't delete them. Everytime I call "eliminar" or "eliminar2" methods I get a "No such object" as result of trying to fetch it. I've checked manually and I see the object exists in my admin panel, with its ID and KIND, so I don't know what am I doing wrong.

Any help would be much appreciated.

4

1 回答 1

0

PM.getObjectByIdKey根据 JDO 规范,不接受对象。它接受一个身份对象,与您获得的类型相同pm.getObjectId(obj);建议您浏览一下 JDO 规范。毫无疑问,如果您检查了此方法返回的内容,您会发现它找不到具有该“身份”的对象,因为 Key 不是身份。你也可以做

pm.getObjectById(Usuari.class, key);

这在 GAE 文档中显示得非常清楚。

仍然不明白为什么用户将@Persistent 放在每个字段上,几乎每种类型都是默认持久的;只会导致代码更不可读。

于 2012-12-27T19:00:22.680 回答