views:

542

answers:

2

The Java documentation says that an app can perform a query during a transaction, but only if it includes an ancestor filter, but there is no documentation for how to do it. Can anyone provide some example code that shows how to do this in the most concise way possible?

A: 

If you are using the low level datastore, it is easy, as "ancestor" is a datastore concept and not a JDO/JPA concept AFAIK.

here is a link to the javadoc showing the Query constructor that takes an ancestor key

Peter Recore
A: 

Try this approach:

// PersistenceManager pm = ...;
Transaction tx = pm.currentTransaction();
User user = userService.currentUser();
List<Account> accounts = new ArrayList<Account>();

try {
    tx.begin();

    Query query = pm.newQuery("select from Customer " +
                              "where user == userParam " +
                              "parameters User userParam");
    List<Customer> customers = (List<Customer>)
    query.execute(user);

    query = pm.newQuery("select from Account " +
                        "where parent-pk == keyParam " +
                        "parameters Key keyParam");
    for (Customer customer : customers) {
        accounts.addAll((List<Account>)
        query.execute(customer.key));
    }

} finally {
    if (tx.isActive()) {
        tx.rollback();
    }
}

More information is available here: http://code.google.com/appengine/docs/java/datastore/transactions.html#Uses_For_Transactions

Antonio