use of org.apache.ignite.table.KeyValueView in project ignite-3 by apache.
the class TransactionsExample method main.
/**
* Main method of the example.
*
* @param args The command line arguments.
* @throws Exception If failed.
*/
public static void main(String[] args) throws Exception {
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/");
Statement stmt = conn.createStatement()) {
stmt.executeUpdate("CREATE TABLE accounts (" + "accountNumber INT PRIMARY KEY," + "firstName VARCHAR," + "lastName VARCHAR," + "balance DOUBLE)");
}
// --------------------------------------------------------------------------------------
//
// Creating a client to connect to the cluster.
//
// --------------------------------------------------------------------------------------
System.out.println("\nConnecting to server...");
try (IgniteClient client = IgniteClient.builder().addresses("127.0.0.1:10800").build()) {
// --------------------------------------------------------------------------------------
//
// Creating an account.
//
// --------------------------------------------------------------------------------------
KeyValueView<AccountKey, Account> accounts = client.tables().table("PUBLIC.accounts").keyValueView(AccountKey.class, Account.class);
final AccountKey key = new AccountKey(123);
accounts.put(null, key, new Account("John", "Doe", 1000.0d));
System.out.println("\nInitial balance: " + accounts.get(null, key).balance);
// --------------------------------------------------------------------------------------
//
// Using synchronous transactional API to update the balance.
//
// --------------------------------------------------------------------------------------
client.transactions().runInTransaction(tx -> {
Account account = accounts.get(tx, key);
account.balance += 200.0d;
accounts.put(tx, key, account);
});
System.out.println("\nBalance after the sync transaction: " + accounts.get(null, key).balance);
// --------------------------------------------------------------------------------------
//
// Using asynchronous transactional API to update the balance.
//
// --------------------------------------------------------------------------------------
CompletableFuture<Void> fut = client.transactions().beginAsync().thenCompose(tx -> accounts.getAsync(tx, key).thenCompose(account -> {
account.balance += 300.0d;
return accounts.putAsync(tx, key, account);
}).thenCompose(ignored -> tx.commitAsync()));
// Wait for completion.
fut.join();
System.out.println("\nBalance after the async transaction: " + accounts.get(null, key).balance);
} finally {
System.out.println("\nDropping the table...");
try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/");
Statement stmt = conn.createStatement()) {
stmt.executeUpdate("DROP TABLE accounts");
}
}
}
Aggregations