views:

36

answers:

1

I need to take an object out of an EntityGroup and store it outside of an entity group, I think the simplest way to explain it is to show the code. In the following code, will the removeMessage() function roll back both calls to the persistence manager?

Is there a way to test this, ie how do I simulate the second makePersistent request failing?

// Not meant to compile, it is for example only
public class UndeliveredMessages {

    private Key key;
    private long count = 0;
    private Set<Message> messages = HashSet<Message>();

    public void removeMessage(Message message) {
            Transaction tx = pm.currentTransaction();
            try {
                    count--;
                    messages.remove(message);
                    pm.makePersistent(this);
                    Message item = new Message();
                    item.setFrom(message.getFrom());
                    item.setTo(message.getTo());
                    item.setText(message.getText());
                    pm.makePersistent(message); // If this one fails, will all of the above be rolled back?
                    tx.commit();
            } finally {
                    if (tx.isActive())
                            tx.rollback();
            }
    }

    public void addMessage(String from, String to, String message) {
            count++;
            messages.put(new Message(from, to, message));
            pm.makePersistent();
    }

    public Message getNextMessage() {
            if(!messages.isEmpty())
                    return messages.iterator().next();

            return null;
    }

}

So in other words, I need to make sure that it doesn't get into a state where a message disappears completely.

+2  A: 

Transactions on App Engine only work within a single entity group - that is, entities with the same parent. In Java, I believe this is implemented by 'owned' entities.

Since the entity you're creating has no parent, it's clearly not in the same entity group, so this won't work. You don't need to simulate anything - the development environment will throw an exception if you try to execute an invalid transaction.

Nick Johnson