Skip to content

Transactions (Experimental)

Hennie Brink edited this page Jun 28, 2016 · 2 revisions

To do inserts and updates in a transaction you have to keep a few things in mind. The CPOrmTransaction will only accept records that extend the CPDefaultRecord class. The reason for this is because android requires backreferences to have long id's as primary keys. You will also have to annotate columns that should be back referenced with the References annotation.

You can create and commit a transaction like this:

CPOrmTransaction transaction = new CPOrmTransaction();

Role role = new Role();
role.setRoleName("Transaction");
transaction.addRecord(role);

User user = new User();
user.setGivenName("Transaction");
user.setFamilyName("Transaction");
user.setUserName("Transaction");
transaction.addRecord(user);

try {
      transaction.commit();
} catch (Exception e) {
   Log.i(TAG, "Failed to apply transaction");
}

Transaction support is experimental and I will probably be trying a couple of different ways to do this in the future, but for now this works. Also note when I say transaction support is experimental I mean the CPOrmTransaction class, the content provider fully supports transactions and you can build your own content provider operations for transactions if this class does not do what you need it to.

Using the CPOrmTransaction class also has some caveats, here are some of the things to keep in mind:

  1. Only inserts and updates are supported.
  2. You have to use the References annotation. You can see an example of this in the example application.
  3. The sequence of the records matter, you have to insert parent records before child records, almost like descending a tree using a depth first algorithm.

Clone this wiki locally