UpdateableDataContext

The UpdateableDataContext interface is a sub-interface of DataContext, and represents any DataContext that is capable of making changes/updates to the data.

The single method for doing updates is executeUpdate(UpdateScript). The UpdateScript argument describes the sequence of updates that you want to perform.

Single updates

There are a number of built-in implementations of UpdateScript which provide out-of-the-box single/atomic updates:

   1 UpdateableDataContext dataContext = ...;
   2 
   3 // InsertInto update:
   4 // INSERT INTO table (name,age) VALUES ('Polly the Sheep', -1)
   5 dataContext.executeUpdate(
   6   new InsertInto(table).value("name", "Polly the Sheep").value("age", -1));
   7 
   8 // Update update:
   9 // UPDATE table SET age = 10 WHERE name = 'Polly the Sheep'
  10 dataContext.executeUpdate(
  11   new Update(table).where("name").eq("Polly the Sheep").value("age", 10));
  12 
  13 // DeleteFrom update:
  14 // DELETE FROM table WHERE name = 'Polly the Sheep'
  15 dataContext.executeUpdate(
  16   new DeleteFrom(table).where("name").eq("Polly the Sheep"));

Custom update script

You can also bundle together updates into a single update script. This will typically mean that transactional attributes are improved and resources remain open during the update, a bit depending on the datastore / DataContext implementation.

   1 UpdateableDataContext dataContext = ...;
   2 dataContext.executeUpdate(new UpdateScript() {
   3   public void run(UpdateCallback callback) {
   4     // INSERT INTO table (name,age) VALUES ('Polly the Sheep', -1)
   5     callback.insertInto(table).value("name", "Polly the Sheep").value("age", -1)).execute();
   6 
   7     // UPDATE table SET age = 10 WHERE name = 'Polly the Sheep'
   8     callback.update(table).where("name").eq("Polly the Sheep").value("age", 10)).execute();
   9 
  10     // DELETE FROM table WHERE name = 'Polly the Sheep'
  11     callback.deleteFrom(table).where("name").eq("Polly the Sheep")).execute();
  12   };
  13 });

Notice also that the UpdateScript interface is a single-method-interface (SAM). This means that from Java 8 and forward, you should be able to provide a closure here instead of an anonymous inner class.

UpdateableDataContext (last edited 2013-08-01 13:53:47 by KasperSorensen)