Cover by Dan Sanderson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Transactions in Java

The JDO and JPA interfaces provide their own mechanisms for formulating transactions. Google’s online documentation describes JDO, and we’ll cover the JPA interface in Chapter 8.

Using the low-level datastore interface, you create an entity in an entity group by providing a Key object that represents an entity in that group to the Entity constructor. You can create this key using the KeyFactory class, or by calling the getKey() method on an Entity instance:

    Key parentKey = KeyFactory.createKey("MessageBoard", "The_Archonville_Times");
    Entity message = new Entity("Message", parentKey);

To create a key for a root entity (an entity without a parent), you call the KeyFactory.createKey() method with a kind (as a string) and the numeric ID or the string key name. To create a key with ancestors using createKey(), you also provide the Key of the parent.

For convenience, the KeyFactory class provides an alternate mechanism for constructing keys with ancestors. The KeyFactory.Builder class represents a key path, which you can extend by calling its addChild() method. The method returns the object, so you can chain multiple calls on a single line. Once the path is complete, you call getKey() to get the Key object:

    Key k = new Builder("MessageBoard", "The_Archonville_times")
                .addChild("Message", 1427)
                .getKey();

To perform multiple operations within a single transaction, you call the beginTransaction() method of the DatastoreService instance. This method returns a Transaction ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required