You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by vk...@apache.org on 2022/01/25 06:39:49 UTC
[ignite-3] branch ignite-3.0.0-alpha4 updated: IGNITE-16244 - Updated examples based on latest changes (#588)
This is an automated email from the ASF dual-hosted git repository.
vkulichenko pushed a commit to branch ignite-3.0.0-alpha4
in repository https://gitbox.apache.org/repos/asf/ignite-3.git
The following commit(s) were added to refs/heads/ignite-3.0.0-alpha4 by this push:
new f95f150 IGNITE-16244 - Updated examples based on latest changes (#588)
f95f150 is described below
commit f95f150dde926d1c617b84a9b7fc34380a87f22d
Author: Valentin Kulichenko <va...@gmail.com>
AuthorDate: Mon Jan 24 22:38:23 2022 -0800
IGNITE-16244 - Updated examples based on latest changes (#588)
---
.../ignite/example/rebalance/RebalanceExample.java | 181 +++++------
.../ignite/example/sql/jdbc/SqlJdbcExample.java | 334 +++++++++------------
.../ignite/example/table/KeyValueViewExample.java | 146 ++++-----
.../example/table/KeyValueViewPojoExample.java | 172 +++++++++++
.../ignite/example/table/RecordViewExample.java | 146 ++++-----
.../example/table/RecordViewPojoExample.java | 163 ++++++++++
.../ignite/example/tx/TransactionsExample.java | 184 ++++++++++++
.../ignite/example/table/TableExamplesTest.java | 28 ++
.../TransactionsExamplesTest.java} | 33 +-
9 files changed, 888 insertions(+), 499 deletions(-)
diff --git a/examples/src/main/java/org/apache/ignite/example/rebalance/RebalanceExample.java b/examples/src/main/java/org/apache/ignite/example/rebalance/RebalanceExample.java
index 3d301ff..5b8843b 100644
--- a/examples/src/main/java/org/apache/ignite/example/rebalance/RebalanceExample.java
+++ b/examples/src/main/java/org/apache/ignite/example/rebalance/RebalanceExample.java
@@ -19,14 +19,13 @@ package org.apache.ignite.example.rebalance;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
import java.util.Set;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgnitionManager;
import org.apache.ignite.client.IgniteClient;
-import org.apache.ignite.internal.schema.configuration.SchemaConfigurationConverter;
-import org.apache.ignite.schema.SchemaBuilders;
-import org.apache.ignite.schema.definition.ColumnType;
-import org.apache.ignite.schema.definition.TableDefinition;
import org.apache.ignite.table.KeyValueView;
import org.apache.ignite.table.Tuple;
@@ -64,132 +63,113 @@ public class RebalanceExample {
public static void main(String[] args) throws Exception {
//--------------------------------------------------------------------------------------
//
- // Starting a server node.
+ // Creating 'accounts' table.
//
- // NOTE: An embedded server node is only needed to invoke the 'createTable' API.
- // In the future releases, this API will be available on the client,
- // eliminating the need to start an embedded server node in this example.
+ //--------------------------------------------------------------------------------------
+
+ try (
+ Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/");
+ Statement stmt = conn.createStatement()
+ ) {
+ stmt.executeUpdate(
+ "CREATE TABLE rebalance ("
+ + "key INT PRIMARY KEY,"
+ + "value VARCHAR)"
+ );
+ }
+
+ //--------------------------------------------------------------------------------------
+ //
+ // Creating a client to connect to the cluster.
//
//--------------------------------------------------------------------------------------
- System.out.println("Starting a server node... Logging to file: example-node.log");
+ System.out.println("\nConnecting to server...");
- System.setProperty("java.util.logging.config.file", "config/java.util.logging.properties");
+ try (IgniteClient client = IgniteClient.builder()
+ .addresses("127.0.0.1:10800")
+ .build()
+ ) {
+ KeyValueView<Tuple, Tuple> kvView = client.tables().table("PUBLIC.rebalance").keyValueView();
- try (Ignite server = IgnitionManager.start(
- "example-node",
- Files.readString(Path.of("config", "ignite-config.json")),
- Path.of("work")
- )) {
//--------------------------------------------------------------------------------------
//
- // Creating a table. The API call below is the equivalent of the following DDL:
- //
- // CREATE TABLE rebalance (
- // key INT PRIMARY KEY,
- // value VARCHAR
- // )
+ // Inserting several key-value pairs into the table.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nCreating a table...");
+ System.out.println("\nInserting key-value pairs...");
- TableDefinition tableDef = SchemaBuilders.tableBuilder("PUBLIC", "rebalance")
- .columns(
- SchemaBuilders.column("key", ColumnType.INT32).build(),
- SchemaBuilders.column("value", ColumnType.string()).asNullable(true).build()
- )
- .withPrimaryKey("key")
- .build();
+ for (int i = 0; i < 10; i++) {
+ Tuple key = Tuple.create().set("key", i);
+ Tuple value = Tuple.create().set("value", "test_" + i);
- server.tables().createTable(tableDef.canonicalName(), tableChange ->
- SchemaConfigurationConverter.convert(tableDef, tableChange)
- .changeReplicas(5)
- .changePartitions(1)
- );
+ kvView.put(null, key, value);
+ }
//--------------------------------------------------------------------------------------
//
- // Creating a client to connect to the cluster.
+ // Retrieving the newly inserted data.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nConnecting to server...");
+ System.out.println("\nRetrieved key-value pairs:");
- try (IgniteClient client = IgniteClient.builder()
- .addresses("127.0.0.1:10800")
- .build()
- ) {
- KeyValueView<Tuple, Tuple> kvView = client.tables().table("PUBLIC.rebalance").keyValueView();
+ for (int i = 0; i < 10; i++) {
+ Tuple key = Tuple.create().set("key", i);
+ Tuple value = kvView.get(null, key);
- //--------------------------------------------------------------------------------------
- //
- // Inserting several key-value pairs into the table.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nInserting key-value pairs...");
-
- for (int i = 0; i < 10; i++) {
- Tuple key = Tuple.create().set("key", i);
- Tuple value = Tuple.create().set("value", "test_" + i);
-
- kvView.put(null, key, value);
- }
-
- //--------------------------------------------------------------------------------------
- //
- // Retrieving the newly inserted data.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nRetrieved key-value pairs:");
+ System.out.println(" " + i + " -> " + value.stringValue("value"));
+ }
- for (int i = 0; i < 10; i++) {
- Tuple key = Tuple.create().set("key", i);
- Tuple value = kvView.get(null, key);
+ //--------------------------------------------------------------------------------------
+ //
+ // Scaling out by adding two more nodes into the topology.
+ //
+ //--------------------------------------------------------------------------------------
- System.out.println(" " + i + " -> " + value.stringValue("value"));
- }
+ System.out.println("\n"
+ + "Run the following commands using the CLI tool to start two more nodes, and then press 'Enter' to continue...\n"
+ + " ignite node start --config=examples/config/ignite-config.json my-first-additional-node\n"
+ + " ignite node start --config=examples/config/ignite-config.json my-second-additional-node");
- //--------------------------------------------------------------------------------------
- //
- // Scaling out by adding two more nodes into the topology.
- //
- //--------------------------------------------------------------------------------------
+ System.in.read();
- System.out.println("\n"
- + "Run the following commands using the CLI tool to start two more nodes, and then press 'Enter' to continue...\n"
- + " ignite node start --config=examples/config/ignite-config.json my-first-additional-node\n"
- + " ignite node start --config=examples/config/ignite-config.json my-second-additional-node");
+ //--------------------------------------------------------------------------------------
+ //
+ // Updating baseline to initiate the data rebalancing process.
+ //
+ // New topology includes the following five nodes:
+ // 1. 'my-first-node' -- the first node started prior to running the example
+ // 2. 'my-second-node' -- the second node started prior to running the example
+ // 3. 'additional-node-1' -- the first node added to the topology
+ // 4. 'additional-node-2' -- the second node added to the topology
+ // 5. 'example-node' -- node that is embedded into the example
+ //
+ // NOTE: An embedded server node is started here for the sole purpose of setting
+ // the baseline. In the future releases, this API will be provided by the
+ // clients as well. In addition, the process will be automated where applicable
+ // to eliminate the need for this manual step.
+ //
+ //--------------------------------------------------------------------------------------
- System.in.read();
+ System.out.println("Starting a server node... Logging to file: example-node.log");
- //--------------------------------------------------------------------------------------
- //
- // Updating baseline to initiate the data rebalancing process.
- //
- // New topology includes the following five nodes:
- // 1. 'my-first-node' -- the first node started prior to running the example
- // 2. 'my-second-node' -- the second node started prior to running the example
- // 3. 'example-node' -- node that is embedded into the example
- // 4. 'additional-node-1' -- the first node added to the topology
- // 5. 'additional-node-2' -- the second node added to the topology
- //
- // NOTE: In the future releases, this API will be provided by the clients as well.
- // In addition, the process will be automated where applicable to eliminate
- // the need for this manual step.
- //
- //--------------------------------------------------------------------------------------
+ System.setProperty("java.util.logging.config.file", "config/java.util.logging.properties");
+ try (Ignite server = IgnitionManager.start(
+ "example-node",
+ Files.readString(Path.of("config", "ignite-config.json")),
+ Path.of("work")
+ )) {
System.out.println("\nUpdating the baseline and rebalancing the data...");
server.setBaseline(Set.of(
"my-first-node",
"my-second-node",
- "example-node",
"my-first-additional-node",
- "my-second-additional-node"
+ "my-second-additional-node",
+ "example-node"
));
//--------------------------------------------------------------------------------------
@@ -207,10 +187,15 @@ public class RebalanceExample {
System.out.println(" " + i + " -> " + value.stringValue("value"));
}
}
+ }
- System.out.println("\nDropping the table and stopping the server...");
+ System.out.println("\nDropping the table...");
- server.tables().dropTable(tableDef.canonicalName());
+ try (
+ Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/");
+ Statement stmt = conn.createStatement()
+ ) {
+ stmt.executeUpdate("DROP TABLE rebalance");
}
}
}
diff --git a/examples/src/main/java/org/apache/ignite/example/sql/jdbc/SqlJdbcExample.java b/examples/src/main/java/org/apache/ignite/example/sql/jdbc/SqlJdbcExample.java
index ab382cd..3a303dd 100644
--- a/examples/src/main/java/org/apache/ignite/example/sql/jdbc/SqlJdbcExample.java
+++ b/examples/src/main/java/org/apache/ignite/example/sql/jdbc/SqlJdbcExample.java
@@ -17,19 +17,11 @@
package org.apache.ignite.example.sql.jdbc;
-import java.nio.file.Files;
-import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
-import org.apache.ignite.Ignite;
-import org.apache.ignite.IgnitionManager;
-import org.apache.ignite.internal.schema.configuration.SchemaConfigurationConverter;
-import org.apache.ignite.schema.SchemaBuilders;
-import org.apache.ignite.schema.definition.ColumnType;
-import org.apache.ignite.schema.definition.TableDefinition;
/**
* This example demonstrates the usage of the Apache Ignite JDBC driver.
@@ -54,236 +46,180 @@ public class SqlJdbcExample {
public static void main(String[] args) throws Exception {
//--------------------------------------------------------------------------------------
//
- // Starting a server node.
- //
- // NOTE: An embedded server node is only needed to invoke the 'createTable' API.
- // In the future releases, this API will be available on the client,
- // eliminating the need to start an embedded server node in this example.
+ // Creating a JDBC connection to connect to the cluster.
//
//--------------------------------------------------------------------------------------
- System.out.println("Starting a server node... Logging to file: example-node.log");
-
- System.setProperty("java.util.logging.config.file", "config/java.util.logging.properties");
+ System.out.println("\nConnecting to server...");
- try (Ignite ignite = IgnitionManager.start(
- "example-node",
- Files.readString(Path.of("config", "ignite-config.json")),
- Path.of("work")
- )) {
+ try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/")) {
//--------------------------------------------------------------------------------------
//
- // Creating 'CITIES' table. The API call below is the equivalent of the following DDL:
+ // Creating tables.
+ //
+ //--------------------------------------------------------------------------------------
+
+ try (Statement stmt = conn.createStatement()) {
+ stmt.executeUpdate(
+ "CREATE TABLE CITIES ("
+ + "ID INT PRIMARY KEY,"
+ + "NAME VARCHAR)"
+ );
+
+ stmt.executeUpdate(
+ "CREATE TABLE ACCOUNTS ("
+ + " ACCOUNT_ID INT PRIMARY KEY,"
+ + " CITY_ID INT,"
+ + " FIRST_NAME VARCHAR,"
+ + " LAST_NAME VARCHAR,"
+ + " BALANCE DOUBLE)"
+ );
+ }
+
+ //--------------------------------------------------------------------------------------
//
- // CREATE TABLE cities (
- // ID INT PRIMARY KEY,
- // NAME VARCHAR
- // )
+ // Populating 'CITIES' table.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nCreating 'CITIES' table...");
+ System.out.println("\nPopulating 'CITIES' table...");
- TableDefinition citiesTableDef = SchemaBuilders.tableBuilder("PUBLIC", "CITIES")
- .columns(
- SchemaBuilders.column("ID", ColumnType.INT32).build(),
- SchemaBuilders.column("NAME", ColumnType.string()).asNullable(true).build()
- )
- .withPrimaryKey("ID")
- .build();
+ try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO CITIES (ID, NAME) VALUES (?, ?)")) {
+ stmt.setInt(1, 1);
+ stmt.setString(2, "Forest Hill");
+ stmt.executeUpdate();
- ignite.tables().createTable(citiesTableDef.canonicalName(), tableChange ->
- SchemaConfigurationConverter.convert(citiesTableDef, tableChange)
- .changeReplicas(1)
- .changePartitions(10)
- );
+ stmt.setInt(1, 2);
+ stmt.setString(2, "Denver");
+ stmt.executeUpdate();
+
+ stmt.setInt(1, 3);
+ stmt.setString(2, "St. Petersburg");
+ stmt.executeUpdate();
+ }
//--------------------------------------------------------------------------------------
//
- // Creating 'ACCOUNTS' table. The API call below is the equivalent of the following DDL:
- //
- // CREATE TABLE ACCOUNTS (
- // ACCOUNT_ID INT PRIMARY KEY,
- // CITY_ID INT,
- // FIRST_NAME VARCHAR,
- // LAST_NAME VARCHAR,
- // BALANCE DOUBLE
- // )
+ // Populating 'ACCOUNTS' table.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nCreating 'ACCOUNTS' table...");
-
- TableDefinition accountsTableDef = SchemaBuilders.tableBuilder("PUBLIC", "ACCOUNTS")
- .columns(
- SchemaBuilders.column("ACCOUNT_ID", ColumnType.INT32).build(),
- SchemaBuilders.column("CITY_ID", ColumnType.INT32).build(),
- SchemaBuilders.column("FIRST_NAME", ColumnType.string()).asNullable(true).build(),
- SchemaBuilders.column("LAST_NAME", ColumnType.string()).asNullable(true).build(),
- SchemaBuilders.column("BALANCE", ColumnType.DOUBLE).asNullable(true).build()
- )
- .withPrimaryKey("ACCOUNT_ID")
- .build();
-
- ignite.tables().createTable(accountsTableDef.canonicalName(), tableChange ->
- SchemaConfigurationConverter.convert(accountsTableDef, tableChange)
- .changeReplicas(1)
- .changePartitions(10)
- );
+ System.out.println("\nPopulating 'ACCOUNTS' table...");
+
+ try (PreparedStatement stmt = conn.prepareStatement(
+ "INSERT INTO ACCOUNTS (ACCOUNT_ID, CITY_ID, FIRST_NAME, LAST_NAME, BALANCE) values (?, ?, ?, ?, ?)")) {
+ stmt.setInt(1, 1);
+ stmt.setInt(2, 1);
+ stmt.setString(3, "John");
+ stmt.setString(4, "Doe");
+ stmt.setDouble(5, 1000.0d);
+ stmt.executeUpdate();
+
+ stmt.setInt(1, 2);
+ stmt.setInt(2, 1);
+ stmt.setString(3, "Jane");
+ stmt.setString(4, "Roe");
+ stmt.setDouble(5, 2000.0d);
+ stmt.executeUpdate();
+
+ stmt.setInt(1, 3);
+ stmt.setInt(2, 2);
+ stmt.setString(3, "Mary");
+ stmt.setString(4, "Major");
+ stmt.setDouble(5, 1500.0d);
+ stmt.executeUpdate();
+
+ stmt.setInt(1, 4);
+ stmt.setInt(2, 3);
+ stmt.setString(3, "Richard");
+ stmt.setString(4, "Miles");
+ stmt.setDouble(5, 1450.0d);
+ stmt.executeUpdate();
+ }
//--------------------------------------------------------------------------------------
//
- // Creating a JDBC connection to connect to the cluster.
+ // Requesting information about all account owners.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nConnecting to server...");
-
- try (Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/")) {
-
- //--------------------------------------------------------------------------------------
- //
- // Populating 'CITIES' table.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nPopulating 'CITIES' table...");
-
- try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO CITIES (ID, NAME) VALUES (?, ?)")) {
- stmt.setInt(1, 1);
- stmt.setString(2, "Forest Hill");
- stmt.executeUpdate();
-
- stmt.setInt(1, 2);
- stmt.setString(2, "Denver");
- stmt.executeUpdate();
-
- stmt.setInt(1, 3);
- stmt.setString(2, "St. Petersburg");
- stmt.executeUpdate();
+ System.out.println("\nAll accounts:");
+
+ try (Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery(
+ "SELECT a.FIRST_NAME, a.LAST_NAME, c.NAME FROM ACCOUNTS a "
+ + "INNER JOIN CITIES c on c.ID = a.CITY_ID ORDER BY a.ACCOUNT_ID")) {
+ while (rs.next()) {
+ System.out.println(" "
+ + rs.getString(1) + ", "
+ + rs.getString(2) + ", "
+ + rs.getString(3));
+ }
}
+ }
- //--------------------------------------------------------------------------------------
- //
- // Populating 'ACCOUNTS' table.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nPopulating 'ACCOUNTS' table...");
-
- try (PreparedStatement stmt = conn.prepareStatement(
- "INSERT INTO ACCOUNTS (ACCOUNT_ID, CITY_ID, FIRST_NAME, LAST_NAME, BALANCE) values (?, ?, ?, ?, ?)")) {
- stmt.setInt(1, 1);
- stmt.setInt(2, 1);
- stmt.setString(3, "John");
- stmt.setString(4, "Doe");
- stmt.setDouble(5, 1000.0d);
- stmt.executeUpdate();
-
- stmt.setInt(1, 2);
- stmt.setInt(2, 1);
- stmt.setString(3, "Jane");
- stmt.setString(4, "Roe");
- stmt.setDouble(5, 2000.0d);
- stmt.executeUpdate();
-
- stmt.setInt(1, 3);
- stmt.setInt(2, 2);
- stmt.setString(3, "Mary");
- stmt.setString(4, "Major");
- stmt.setDouble(5, 1500.0d);
- stmt.executeUpdate();
-
- stmt.setInt(1, 4);
- stmt.setInt(2, 3);
- stmt.setString(3, "Richard");
- stmt.setString(4, "Miles");
- stmt.setDouble(5, 1450.0d);
- stmt.executeUpdate();
- }
+ //--------------------------------------------------------------------------------------
+ //
+ // Requesting accounts with balances lower than 1,500.
+ //
+ //--------------------------------------------------------------------------------------
- //--------------------------------------------------------------------------------------
- //
- // Requesting information about all account owners.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nAll accounts:");
-
- try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery(
- "SELECT a.FIRST_NAME, a.LAST_NAME, c.NAME FROM ACCOUNTS a "
- + "INNER JOIN CITIES c on c.ID = a.CITY_ID ORDER BY a.ACCOUNT_ID")) {
- while (rs.next()) {
- System.out.println(" "
- + rs.getString(1) + ", "
- + rs.getString(2) + ", "
- + rs.getString(3));
- }
+ System.out.println("\nAccounts with balance lower than 1,500:");
+
+ try (Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery(
+ "SELECT a.FIRST_NAME, a.LAST_NAME, a.BALANCE FROM ACCOUNTS a WHERE a.BALANCE < 1500.0 "
+ + "ORDER BY a.ACCOUNT_ID")) {
+ while (rs.next()) {
+ System.out.println(" "
+ + rs.getString(1) + ", "
+ + rs.getString(2) + ", "
+ + rs.getDouble(3));
}
}
+ }
- //--------------------------------------------------------------------------------------
- //
- // Requesting accounts with balances lower than 1,500.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nAccounts with balance lower than 1,500:");
-
- try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery(
- "SELECT a.FIRST_NAME, a.LAST_NAME, a.BALANCE FROM ACCOUNTS a WHERE a.BALANCE < 1500.0 "
- + "ORDER BY a.ACCOUNT_ID")) {
- while (rs.next()) {
- System.out.println(" "
- + rs.getString(1) + ", "
- + rs.getString(2) + ", "
- + rs.getDouble(3));
- }
- }
- }
+ //--------------------------------------------------------------------------------------
+ //
+ // Deleting one of the accounts.
+ //
+ //--------------------------------------------------------------------------------------
- //--------------------------------------------------------------------------------------
- //
- // Deleting one of the accounts.
- //
- //--------------------------------------------------------------------------------------
+ System.out.println("\nDeleting one of the accounts...");
- System.out.println("\nDeleting one of the accounts...");
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM ACCOUNTS WHERE ACCOUNT_ID = ?")) {
+ stmt.setInt(1, 1);
+ stmt.executeUpdate();
+ }
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM ACCOUNTS WHERE ACCOUNT_ID = ?")) {
- stmt.setInt(1, 1);
- stmt.executeUpdate();
- }
+ //--------------------------------------------------------------------------------------
+ //
+ // Requesting information about all account owners once again
+ // to verify that the account was actually deleted.
+ //
+ //--------------------------------------------------------------------------------------
- //--------------------------------------------------------------------------------------
- //
- // Requesting information about all account owners once again
- // to verify that the account was actually deleted.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nAll accounts:");
-
- try (Statement stmt = conn.createStatement()) {
- try (ResultSet rs = stmt.executeQuery(
- "SELECT a.FIRST_NAME, a.LAST_NAME, c.NAME FROM ACCOUNTS a "
- + "INNER JOIN CITIES c on c.ID = a.CITY_ID ORDER BY a.ACCOUNT_ID")) {
- while (rs.next()) {
- System.out.println(" "
- + rs.getString(1) + ", "
- + rs.getString(2) + ", "
- + rs.getString(3));
- }
+ System.out.println("\nAll accounts:");
+
+ try (Statement stmt = conn.createStatement()) {
+ try (ResultSet rs = stmt.executeQuery(
+ "SELECT a.FIRST_NAME, a.LAST_NAME, c.NAME FROM ACCOUNTS a "
+ + "INNER JOIN CITIES c on c.ID = a.CITY_ID ORDER BY a.ACCOUNT_ID")) {
+ while (rs.next()) {
+ System.out.println(" "
+ + rs.getString(1) + ", "
+ + rs.getString(2) + ", "
+ + rs.getString(3));
}
}
}
- System.out.println("\nDropping tables and stopping the server...");
+ System.out.println("\nDropping the tables...");
- ignite.tables().dropTable(citiesTableDef.canonicalName());
- ignite.tables().dropTable(accountsTableDef.canonicalName());
+ try (Statement stmt = conn.createStatement()) {
+ stmt.executeUpdate("DROP TABLE ACCOUNTS");
+ stmt.executeUpdate("DROP TABLE CITIES");
+ }
}
}
}
diff --git a/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewExample.java b/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewExample.java
index 0943ae5..c5a0110 100644
--- a/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewExample.java
+++ b/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewExample.java
@@ -17,15 +17,10 @@
package org.apache.ignite.example.table;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import org.apache.ignite.Ignite;
-import org.apache.ignite.IgnitionManager;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
import org.apache.ignite.client.IgniteClient;
-import org.apache.ignite.internal.schema.configuration.SchemaConfigurationConverter;
-import org.apache.ignite.schema.SchemaBuilders;
-import org.apache.ignite.schema.definition.ColumnType;
-import org.apache.ignite.schema.definition.TableDefinition;
import org.apache.ignite.table.KeyValueView;
import org.apache.ignite.table.Tuple;
@@ -52,112 +47,85 @@ public class KeyValueViewExample {
public static void main(String[] args) throws Exception {
//--------------------------------------------------------------------------------------
//
- // Starting a server node.
- //
- // NOTE: An embedded server node is only needed to invoke the 'createTable' API.
- // In the future releases, this API will be available on the client,
- // eliminating the need to start an embedded server node in this example.
+ // Creating 'accounts' table.
//
//--------------------------------------------------------------------------------------
- System.out.println("Starting a server node... Logging to file: example-node.log");
+ 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)"
+ );
+ }
- System.setProperty("java.util.logging.config.file", "config/java.util.logging.properties");
+ //--------------------------------------------------------------------------------------
+ //
+ // Creating a client to connect to the cluster.
+ //
+ //--------------------------------------------------------------------------------------
+
+ System.out.println("\nConnecting to server...");
- try (Ignite server = IgnitionManager.start(
- "example-node",
- Files.readString(Path.of("config", "ignite-config.json")),
- Path.of("work")
- )) {
+ try (IgniteClient client = IgniteClient.builder()
+ .addresses("127.0.0.1:10800")
+ .build()
+ ) {
//--------------------------------------------------------------------------------------
//
- // Creating 'accounts' table. The API call below is the equivalent of the following DDL:
- //
- // CREATE TABLE accounts (
- // accountNumber INT PRIMARY KEY,
- // firstName VARCHAR,
- // lastName VARCHAR,
- // balance DOUBLE
- // )
+ // Creating a key-value view for the 'accounts' table.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nCreating 'accounts' table...");
-
- TableDefinition accountsTableDef = SchemaBuilders.tableBuilder("PUBLIC", "accounts")
- .columns(
- SchemaBuilders.column("accountNumber", ColumnType.INT32).build(),
- SchemaBuilders.column("firstName", ColumnType.string()).asNullable(true).build(),
- SchemaBuilders.column("lastName", ColumnType.string()).asNullable(true).build(),
- SchemaBuilders.column("balance", ColumnType.DOUBLE).asNullable(true).build()
- )
- .withPrimaryKey("accountNumber")
- .build();
-
- server.tables().createTable(accountsTableDef.canonicalName(), tableChange ->
- SchemaConfigurationConverter.convert(accountsTableDef, tableChange)
- .changeReplicas(1)
- .changePartitions(10)
- );
+ KeyValueView<Tuple, Tuple> kvView = client.tables().table("PUBLIC.accounts").keyValueView();
//--------------------------------------------------------------------------------------
//
- // Creating a client to connect to the cluster.
+ // Performing the 'put' operation.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nConnecting to server...");
+ System.out.println("\nInserting a key-value pair into the 'accounts' table...");
- try (IgniteClient client = IgniteClient.builder()
- .addresses("127.0.0.1:10800")
- .build()
- ) {
- //--------------------------------------------------------------------------------------
- //
- // Creating a key-value view for the 'accounts' table.
- //
- //--------------------------------------------------------------------------------------
+ Tuple key = Tuple.create()
+ .set("accountNumber", 123456);
- KeyValueView<Tuple, Tuple> kvView = client.tables().table("PUBLIC.accounts").keyValueView();
+ Tuple value = Tuple.create()
+ .set("firstName", "Val")
+ .set("lastName", "Kulichenko")
+ .set("balance", 100.00d);
- //--------------------------------------------------------------------------------------
- //
- // Performing the 'put' operation.
- //
- //--------------------------------------------------------------------------------------
+ kvView.put(null, key, value);
- System.out.println("\nInserting a key-value pair into the 'accounts' table...");
-
- Tuple key = Tuple.create()
- .set("accountNumber", 123456);
-
- Tuple value = Tuple.create()
- .set("firstName", "Val")
- .set("lastName", "Kulichenko")
- .set("balance", 100.00d);
-
- kvView.put(null, key, value);
+ //--------------------------------------------------------------------------------------
+ //
+ // Performing the 'get' operation.
+ //
+ //--------------------------------------------------------------------------------------
- //--------------------------------------------------------------------------------------
- //
- // Performing the 'get' operation.
- //
- //--------------------------------------------------------------------------------------
+ System.out.println("\nRetrieving a value using KeyValueView API...");
- System.out.println("\nRetrieving a value using KeyValueView API...");
+ value = kvView.get(null, key);
- value = kvView.get(null, key);
+ System.out.println(
+ "\nRetrieved value:\n"
+ + " Account Number: " + key.intValue("accountNumber") + '\n'
+ + " Owner: " + value.stringValue("firstName") + " " + value.stringValue("lastName") + '\n'
+ + " Balance: $" + value.doubleValue("balance"));
+ } finally {
+ System.out.println("\nDropping the table...");
- System.out.println(
- "\nRetrieved value:\n"
- + " Account Number: " + key.intValue("accountNumber") + '\n'
- + " Owner: " + value.stringValue("firstName") + " " + value.stringValue("lastName") + '\n'
- + " Balance: $" + value.doubleValue("balance"));
+ try (
+ Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/");
+ Statement stmt = conn.createStatement()
+ ) {
+ stmt.executeUpdate("DROP TABLE accounts");
}
-
- System.out.println("\nDropping the table and stopping the server...");
-
- server.tables().dropTable(accountsTableDef.canonicalName());
}
}
}
diff --git a/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewPojoExample.java b/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewPojoExample.java
new file mode 100644
index 0000000..9e9f6f0
--- /dev/null
+++ b/examples/src/main/java/org/apache/ignite/example/table/KeyValueViewPojoExample.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.example.table;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+import org.apache.ignite.client.IgniteClient;
+import org.apache.ignite.table.KeyValueView;
+
+/**
+ * This example demonstrates the usage of the {@link KeyValueView} API with user-defined POJOs.
+ *
+ * <p>To run the example, do the following:
+ * <ol>
+ * <li>Import the examples project into you IDE.</li>
+ * <li>
+ * Start a server node using the CLI tool:<br>
+ * {@code ignite node start --config=$IGNITE_HOME/examples/config/ignite-config.json my-first-node}
+ * </li>
+ * <li>Run the example in the IDE.</li>
+ * </ol>
+ */
+public class KeyValueViewPojoExample {
+ /**
+ * Main method of the example.
+ *
+ * @param args The command line arguments.
+ * @throws Exception If failed.
+ */
+ public static void main(String[] args) throws Exception {
+ //--------------------------------------------------------------------------------------
+ //
+ // Creating 'accounts' table.
+ //
+ //--------------------------------------------------------------------------------------
+
+ 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 a key-value view for the 'accounts' table.
+ //
+ //--------------------------------------------------------------------------------------
+
+ KeyValueView<AccountKey, Account> kvView = client.tables()
+ .table("PUBLIC.accounts")
+ .keyValueView(AccountKey.class, Account.class);
+
+ //--------------------------------------------------------------------------------------
+ //
+ // Performing the 'put' operation.
+ //
+ //--------------------------------------------------------------------------------------
+
+ System.out.println("\nInserting a key-value pair into the 'accounts' table...");
+
+ AccountKey key = new AccountKey(123456);
+
+ Account value = new Account(
+ "Val",
+ "Kulichenko",
+ 100.00d
+ );
+
+ kvView.put(null, key, value);
+
+ //--------------------------------------------------------------------------------------
+ //
+ // Performing the 'get' operation.
+ //
+ //--------------------------------------------------------------------------------------
+
+ System.out.println("\nRetrieving a value using KeyValueView API...");
+
+ value = kvView.get(null, key);
+
+ System.out.println(
+ "\nRetrieved value:\n"
+ + " Account Number: " + key.accountNumber + '\n'
+ + " Owner: " + value.firstName + " " + value.lastName + '\n'
+ + " Balance: $" + value.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");
+ }
+ }
+ }
+
+ /**
+ * POJO class that represents key.
+ */
+ static class AccountKey {
+ int accountNumber;
+
+ /**
+ * Default constructor (required for deserialization).
+ */
+ @SuppressWarnings("unused")
+ public AccountKey() {
+ }
+
+ public AccountKey(int accountNumber) {
+ this.accountNumber = accountNumber;
+ }
+ }
+
+ /**
+ * POJO class that represents value.
+ */
+ static class Account {
+ String firstName;
+ String lastName;
+ double balance;
+
+ /**
+ * Default constructor (required for deserialization).
+ */
+ @SuppressWarnings("unused")
+ public Account() {
+ }
+
+ public Account(String firstName, String lastName, double balance) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.balance = balance;
+ }
+ }
+}
diff --git a/examples/src/main/java/org/apache/ignite/example/table/RecordViewExample.java b/examples/src/main/java/org/apache/ignite/example/table/RecordViewExample.java
index a1d11fb..89d5468 100644
--- a/examples/src/main/java/org/apache/ignite/example/table/RecordViewExample.java
+++ b/examples/src/main/java/org/apache/ignite/example/table/RecordViewExample.java
@@ -17,15 +17,10 @@
package org.apache.ignite.example.table;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import org.apache.ignite.Ignite;
-import org.apache.ignite.IgnitionManager;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
import org.apache.ignite.client.IgniteClient;
-import org.apache.ignite.internal.schema.configuration.SchemaConfigurationConverter;
-import org.apache.ignite.schema.SchemaBuilders;
-import org.apache.ignite.schema.definition.ColumnType;
-import org.apache.ignite.schema.definition.TableDefinition;
import org.apache.ignite.table.RecordView;
import org.apache.ignite.table.Tuple;
@@ -52,112 +47,85 @@ public class RecordViewExample {
public static void main(String[] args) throws Exception {
//--------------------------------------------------------------------------------------
//
- // Starting a server node.
- //
- // NOTE: An embedded server node is only needed to invoke the 'createTable' API.
- // In the future releases, this API will be available on the client,
- // eliminating the need to start an embedded server node in this example.
+ // Creating 'accounts' table.
//
//--------------------------------------------------------------------------------------
- System.out.println("Starting a server node... Logging to file: example-node.log");
+ 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)"
+ );
+ }
- System.setProperty("java.util.logging.config.file", "config/java.util.logging.properties");
+ //--------------------------------------------------------------------------------------
+ //
+ // Creating a client to connect to the cluster.
+ //
+ //--------------------------------------------------------------------------------------
+
+ System.out.println("\nConnecting to server...");
- try (Ignite server = IgnitionManager.start(
- "example-node",
- Files.readString(Path.of("config", "ignite-config.json")),
- Path.of("work")
- )) {
+ try (IgniteClient client = IgniteClient.builder()
+ .addresses("127.0.0.1:10800")
+ .build()
+ ) {
//--------------------------------------------------------------------------------------
//
- // Creating 'accounts' table. The API call below is the equivalent of the following DDL:
- //
- // CREATE TABLE accounts (
- // accountNumber INT PRIMARY KEY,
- // firstName VARCHAR,
- // lastName VARCHAR,
- // balance DOUBLE
- // )
+ // Creating a record view for the 'accounts' table.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nCreating 'accounts' table...");
-
- TableDefinition accountsTableDef = SchemaBuilders.tableBuilder("PUBLIC", "accounts")
- .columns(
- SchemaBuilders.column("accountNumber", ColumnType.INT32).build(),
- SchemaBuilders.column("firstName", ColumnType.string()).asNullable(true).build(),
- SchemaBuilders.column("lastName", ColumnType.string()).asNullable(true).build(),
- SchemaBuilders.column("balance", ColumnType.DOUBLE).asNullable(true).build()
- )
- .withPrimaryKey("accountNumber")
- .build();
-
- server.tables().createTable(accountsTableDef.canonicalName(), tableChange ->
- SchemaConfigurationConverter.convert(accountsTableDef, tableChange)
- .changeReplicas(1)
- .changePartitions(10)
- );
+ RecordView<Tuple> accounts = client.tables().table("PUBLIC.accounts").recordView();
//--------------------------------------------------------------------------------------
//
- // Creating a client to connect to the cluster.
+ // Performing the 'insert' operation.
//
//--------------------------------------------------------------------------------------
- System.out.println("\nConnecting to server...");
+ System.out.println("\nInserting a record into the 'accounts' table...");
- try (IgniteClient client = IgniteClient.builder()
- .addresses("127.0.0.1:10800")
- .build()
- ) {
- //--------------------------------------------------------------------------------------
- //
- // Creating a record view for the 'accounts' table.
- //
- //--------------------------------------------------------------------------------------
+ Tuple newAccountTuple = Tuple.create()
+ .set("accountNumber", 123456)
+ .set("firstName", "Val")
+ .set("lastName", "Kulichenko")
+ .set("balance", 100.00d);
- RecordView<Tuple> accounts = client.tables().table("PUBLIC.accounts").recordView();
+ accounts.insert(null, newAccountTuple);
- //--------------------------------------------------------------------------------------
- //
- // Performing the 'insert' operation.
- //
- //--------------------------------------------------------------------------------------
-
- System.out.println("\nInserting a record into the 'accounts' table...");
-
- Tuple newAccountTuple = Tuple.create()
- .set("accountNumber", 123456)
- .set("firstName", "Val")
- .set("lastName", "Kulichenko")
- .set("balance", 100.00d);
-
- accounts.insert(null, newAccountTuple);
+ //--------------------------------------------------------------------------------------
+ //
+ // Performing the 'get' operation.
+ //
+ //--------------------------------------------------------------------------------------
- //--------------------------------------------------------------------------------------
- //
- // Performing the 'get' operation.
- //
- //--------------------------------------------------------------------------------------
+ System.out.println("\nRetrieving a record using RecordView API...");
- System.out.println("\nRetrieving a record using RecordView API...");
+ Tuple accountNumberTuple = Tuple.create().set("accountNumber", 123456);
- Tuple accountNumberTuple = Tuple.create().set("accountNumber", 123456);
+ Tuple accountTuple = accounts.get(null, accountNumberTuple);
- Tuple accountTuple = accounts.get(null, accountNumberTuple);
+ System.out.println(
+ "\nRetrieved record:\n"
+ + " Account Number: " + accountTuple.intValue("accountNumber") + '\n'
+ + " Owner: " + accountTuple.stringValue("firstName") + " " + accountTuple.stringValue("lastName") + '\n'
+ + " Balance: $" + accountTuple.doubleValue("balance"));
+ } finally {
+ System.out.println("\nDropping the table...");
- System.out.println(
- "\nRetrieved record:\n"
- + " Account Number: " + accountTuple.intValue("accountNumber") + '\n'
- + " Owner: " + accountTuple.stringValue("firstName") + " " + accountTuple.stringValue("lastName") + '\n'
- + " Balance: $" + accountTuple.doubleValue("balance"));
+ try (
+ Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1:10800/");
+ Statement stmt = conn.createStatement()
+ ) {
+ stmt.executeUpdate("DROP TABLE accounts");
}
-
- System.out.println("\nDropping the table and stopping the server...");
-
- server.tables().dropTable(accountsTableDef.canonicalName());
}
}
}
diff --git a/examples/src/main/java/org/apache/ignite/example/table/RecordViewPojoExample.java b/examples/src/main/java/org/apache/ignite/example/table/RecordViewPojoExample.java
new file mode 100644
index 0000000..abbbde4
--- /dev/null
+++ b/examples/src/main/java/org/apache/ignite/example/table/RecordViewPojoExample.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.example.table;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+import org.apache.ignite.client.IgniteClient;
+import org.apache.ignite.table.RecordView;
+
+/**
+ * This example demonstrates the usage of the {@link RecordView} API with user-defined POJOs.
+ *
+ * <p>To run the example, do the following:
+ * <ol>
+ * <li>Import the examples project into you IDE.</li>
+ * <li>
+ * Start a server node using the CLI tool:<br>
+ * {@code ignite node start --config=$IGNITE_HOME/examples/config/ignite-config.json my-first-node}
+ * </li>
+ * <li>Run the example in the IDE.</li>
+ * </ol>
+ */
+public class RecordViewPojoExample {
+ /**
+ * Main method of the example.
+ *
+ * @param args The command line arguments.
+ * @throws Exception If failed.
+ */
+ public static void main(String[] args) throws Exception {
+ //--------------------------------------------------------------------------------------
+ //
+ // Creating 'accounts' table.
+ //
+ //--------------------------------------------------------------------------------------
+
+ 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 a record view for the 'accounts' table.
+ //
+ //--------------------------------------------------------------------------------------
+
+ RecordView<Account> accounts = client.tables()
+ .table("PUBLIC.accounts")
+ .recordView(Account.class);
+
+ //--------------------------------------------------------------------------------------
+ //
+ // Performing the 'insert' operation.
+ //
+ //--------------------------------------------------------------------------------------
+
+ System.out.println("\nInserting a record into the 'accounts' table...");
+
+ Account newAccount = new Account(
+ 123456,
+ "Val",
+ "Kulichenko",
+ 100.00d
+ );
+
+ accounts.insert(null, newAccount);
+
+ //--------------------------------------------------------------------------------------
+ //
+ // Performing the 'get' operation.
+ //
+ //--------------------------------------------------------------------------------------
+
+ System.out.println("\nRetrieving a record using RecordView API...");
+
+ Account account = accounts.get(null, new Account(123456));
+
+ System.out.println(
+ "\nRetrieved record:\n"
+ + " Account Number: " + account.accountNumber + '\n'
+ + " Owner: " + account.firstName + " " + account.lastName + '\n'
+ + " Balance: $" + account.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");
+ }
+ }
+ }
+
+ /**
+ * POJO class that represents record.
+ */
+ static class Account {
+ int accountNumber;
+ String firstName;
+ String lastName;
+ double balance;
+
+ /**
+ * Default constructor (required for deserialization).
+ */
+ @SuppressWarnings("unused")
+ public Account() {
+ }
+
+ public Account(int accountNumber) {
+ this.accountNumber = accountNumber;
+
+ firstName = null;
+ lastName = null;
+ balance = 0.0d;
+ }
+
+ public Account(int accountNumber, String firstName, String lastName, double balance) {
+ this.accountNumber = accountNumber;
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.balance = balance;
+ }
+ }
+}
diff --git a/examples/src/main/java/org/apache/ignite/example/tx/TransactionsExample.java b/examples/src/main/java/org/apache/ignite/example/tx/TransactionsExample.java
new file mode 100644
index 0000000..c77585c
--- /dev/null
+++ b/examples/src/main/java/org/apache/ignite/example/tx/TransactionsExample.java
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.example.tx;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.client.IgniteClient;
+import org.apache.ignite.table.KeyValueView;
+import org.apache.ignite.tx.IgniteTransactions;
+
+/**
+ * This example demonstrates the usage of the {@link IgniteTransactions} API.
+ *
+ * <p>To run the example, do the following:
+ * <ol>
+ * <li>Import the examples project into you IDE.</li>
+ * <li>
+ * Start a server node using the CLI tool:<br>
+ * {@code ignite node start --config=$IGNITE_HOME/examples/config/ignite-config.json my-first-node}
+ * </li>
+ * <li>Run the example in the IDE.</li>
+ * </ol>
+ */
+public class TransactionsExample {
+ /**
+ * Main method of the example.
+ *
+ * @param args The command line arguments.
+ * @throws Exception If failed.
+ */
+ public static void main(String[] args) throws Exception {
+ //--------------------------------------------------------------------------------------
+ //
+ // Creating 'accounts' table.
+ //
+ //--------------------------------------------------------------------------------------
+
+ 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");
+ }
+ }
+ }
+
+ /**
+ * POJO class that represents key.
+ */
+ static class AccountKey {
+ int accountNumber;
+
+ /**
+ * Default constructor (required for deserialization).
+ */
+ @SuppressWarnings("unused")
+ public AccountKey() {
+ }
+
+ public AccountKey(int accountNumber) {
+ this.accountNumber = accountNumber;
+ }
+ }
+
+ /**
+ * POJO class that represents value.
+ */
+ static class Account {
+ String firstName;
+ String lastName;
+ double balance;
+
+ /**
+ * Default constructor (required for deserialization).
+ */
+ @SuppressWarnings("unused")
+ public Account() {
+ }
+
+ public Account(String firstName, String lastName, double balance) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.balance = balance;
+ }
+ }
+}
diff --git a/examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java b/examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java
index bb8b955..5c179b5 100644
--- a/examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java
+++ b/examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java
@@ -53,6 +53,20 @@ public class TableExamplesTest {
}
/**
+ * Runs RecordViewPojoExample.
+ *
+ * @throws Exception If failed and checks its output.
+ */
+ @Test
+ public void testRecordViewPojoExample() throws Exception {
+ ExampleTestUtils.assertConsoleOutputContains(RecordViewPojoExample::main, EMPTY_ARGS,
+ "\nRetrieved record:\n"
+ + " Account Number: 123456\n"
+ + " Owner: Val Kulichenko\n"
+ + " Balance: $100.0\n");
+ }
+
+ /**
* Runs KeyValueViewExample and checks its output.
*
* @throws Exception If failed.
@@ -67,6 +81,20 @@ public class TableExamplesTest {
}
/**
+ * Runs KeyValueViewPojoExample and checks its output.
+ *
+ * @throws Exception If failed.
+ */
+ @Test
+ public void testKeyValueViewPojoExample() throws Exception {
+ ExampleTestUtils.assertConsoleOutputContains(KeyValueViewPojoExample::main, EMPTY_ARGS,
+ "\nRetrieved value:\n"
+ + " Account Number: 123456\n"
+ + " Owner: Val Kulichenko\n"
+ + " Balance: $100.0\n");
+ }
+
+ /**
* Start node.
*
* @param workDir Work directory for the started node. Must not be {@code null}.
diff --git a/examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java b/examples/src/test/java/org/apache/ignite/example/tx/TransactionsExamplesTest.java
similarity index 69%
copy from examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java
copy to examples/src/test/java/org/apache/ignite/example/tx/TransactionsExamplesTest.java
index bb8b955..8a59175 100644
--- a/examples/src/test/java/org/apache/ignite/example/table/TableExamplesTest.java
+++ b/examples/src/test/java/org/apache/ignite/example/tx/TransactionsExamplesTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.ignite.example.table;
+package org.apache.ignite.example.tx;
import java.io.IOException;
import java.nio.file.Files;
@@ -31,39 +31,24 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
- * These tests check that all table examples pass correctly.
+ * Tests for transactional examples.
*/
@ExtendWith(WorkDirectoryExtension.class)
-public class TableExamplesTest {
+public class TransactionsExamplesTest {
/** Empty argument to invoke an example. */
protected static final String[] EMPTY_ARGS = new String[0];
/**
- * Runs RecordViewExample.
- *
- * @throws Exception If failed and checks its output.
- */
- @Test
- public void testRecordViewExample() throws Exception {
- ExampleTestUtils.assertConsoleOutputContains(RecordViewExample::main, EMPTY_ARGS,
- "\nRetrieved record:\n"
- + " Account Number: 123456\n"
- + " Owner: Val Kulichenko\n"
- + " Balance: $100.0\n");
- }
-
- /**
- * Runs KeyValueViewExample and checks its output.
+ * Runs TransactionsExample and checks its output.
*
* @throws Exception If failed.
*/
@Test
- public void testKeyValueViewExample() throws Exception {
- ExampleTestUtils.assertConsoleOutputContains(KeyValueViewExample::main, EMPTY_ARGS,
- "\nRetrieved value:\n"
- + " Account Number: 123456\n"
- + " Owner: Val Kulichenko\n"
- + " Balance: $100.0\n");
+ public void testTransactionsExample() throws Exception {
+ ExampleTestUtils.assertConsoleOutputContains(TransactionsExample::main, EMPTY_ARGS,
+ "Initial balance: 1000.0",
+ "Balance after the sync transaction: 1200.0",
+ "Balance after the async transaction: 1500.0");
}
/**