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.