This tutorial shows you how build a simple Java application with CockroachDB using a PostgreSQL-compatible driver or ORM. We’ve tested and can recommend the Java jdbc driver and the Hibernate ORM, so those are featured here.

Before You Begin

Make sure you have already installed CockroachDB.

Step 1. Install the Java jdbc driver

Download and set up the Java jdbc driver as described in the official documentation.

Step 1. Install the Gradle build tool

This tutorial uses the Gradle build tool to get all dependencies for your application, including the Hibernate ORM. To install Gradle, run the following command:

# On Mac:
$ brew install gradle

# On Ubuntu Linux:
$ apt-get install gradle

For other ways to install Gradle, see the official documentation.

Step 2. Start a cluster

For the purpose of this tutorial, you need only one CockroachDB node running in insecure mode:

# Start node 1:
$ cockroach start --background \
--store=hello-1

But as you might’ve seen in the Start a Local Cluster tutorial, it’s incredibly easy to start and join addition nodes, if you want to simulate a real cluster:

# Start node 2:
$ cockroach start --background \
--store=hello-2 \
--port=26258 \
--http-port=8081 \
--join=localhost:26257

# Start node 3:
$ cockroach start --background \
--store=hello-3 \
--port=26259 \
--http-port=8082 \
--join=localhost:26257

Step 3. Create a user

As the root user, use the cockroach user command to create a new user, maxroach.

$ cockroach user set maxroach

Step 4. Create a database and grant privileges

As the root user, use the built-in SQL client to create a bank database.

$ cockroach sql -e 'CREATE DATABASE bank'

Then grant privileges to the maxroach user

$ cockroach sql -e 'GRANT ALL ON DATABASE bank TO maxroach'

Step 5. Run the Java code

Basic Statements

The following code connects as the maxroach user and executes some basic SQL statements, creating a table, inserting rows, and reading and printing the rows.

Copy the code or download it directly.

import java.sql.*;

/*
You can compile and run this example with a command like:
  javac BasicSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar BasicSample
You can download the postgres JDBC driver jar from https://jdbc.postgresql.org.
*/
public class BasicSample {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // Load the postgres JDBC driver.
        Class.forName("org.postgresql.Driver");

        // Connect to the "bank" database.
        Connection db = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable", "maxroach", "");

        try {
            // Create the "accounts" table.
            db.createStatement().execute("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)");

            // Insert two rows into the "accounts" table.
            db.createStatement().execute("INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)");

            // Print out the balances.
            System.out.println("Initial balances:");
            ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts");
            while (res.next()) {
                System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance"));
            }
        } finally {
            // Close the database connection.
            db.close();
        }
    }
}

Transaction (with retry logic)

The following code again connects as the maxroach user but this time executes a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted.

Copy the code or download it directly.

Because the CockroachDB transaction model requires the client to initiate retries in the case of contention, CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code. For more details, see Transaction Retries.
import java.sql.*;

/*
  You can compile and run this example with a command like:
  javac TxnSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar TxnSample
  You can download the postgres JDBC driver jar from https://jdbc.postgresql.org.
*/

class InsufficientBalanceException extends Exception {}
class AccountNotFoundException extends Exception {
    public int account;
    public AccountNotFoundException(int account) {
        this.account = account;
    }
}

// A simple interface that provides a retryable lambda expression.
interface RetryableTransaction {
    public void run(Connection conn)
        throws SQLException, InsufficientBalanceException, AccountNotFoundException;
}

public class TxnSample {
    public static RetryableTransaction transferFunds(int from, int to, int amount) {
        return new RetryableTransaction() {
            public void run(Connection conn)
                throws SQLException, InsufficientBalanceException, AccountNotFoundException {
                // Check the current balance.
                ResultSet res = conn.createStatement().executeQuery("SELECT balance FROM accounts WHERE id = " + from);
                if(!res.next()) {
                    throw new AccountNotFoundException(from);
                }
                int balance = res.getInt("balance");
                if(balance < from) {
                    throw new InsufficientBalanceException();
                }
                // Perform the transfer.
                conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance - " + amount + " where id = " + from);
                conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance + " + amount + " where id = " + to);
            }
        };
    }

    public static void retryTransaction(Connection conn, RetryableTransaction tx)
        throws SQLException, InsufficientBalanceException, AccountNotFoundException {
        Savepoint sp = conn.setSavepoint("cockroach_restart");
        while(true) {
            try {
                // Attempt the transaction.
                tx.run(conn);

                // If we reach this point, commit the transaction,
                // which implicitly releases the savepoint.
                conn.commit();
                break;
            } catch(SQLException e) {
                // Check if the error code indicates a SERIALIZATION_FAILURE.
                if(e.getErrorCode() == 40001) {
                    // Signal the database that we will attempt a retry.
                    conn.rollback(sp);
                }
                // This is a not a serialization failure, pass it up the chain.
                throw e;
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // Load the postgres JDBC driver.
        Class.forName("org.postgresql.Driver");

        // Connect to the "bank" database.
        Connection db = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable", "maxroach", "");
            try {
                // We need to turn off autocommit mode to allow for
                // multi-statement transactions.
                db.setAutoCommit(false);
                // Perform the transfer. This assumes the table has
                // already been set up as in the "Build a Test App"
                // tutorial.
                RetryableTransaction transfer = transferFunds(1, 2, 100);
                retryTransaction(db, transfer);
                // Check balances after transfer.
                ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts");
                while (res.next()) {
                    System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance"));
                }
            } catch(InsufficientBalanceException e) {
                System.out.println("Insufficient balance");
            } catch(AccountNotFoundException e) {
                System.out.println("No users in the table with id " + e.account);
            } catch(SQLException e) {
                System.out.println("SQLException encountered:" + e);
            } finally {
                // Close the database connection.
                db.close();
            }
    }
}

After running the code, to verify that funds were, in fact, transferred from one account to another, you can again use the built-in SQL client:

$ cockroach sql -e 'SELECT id, balance FROM accounts' --database=bank
+----+---------+
| id | balance |
+----+---------+
|  1 |     900 |
|  2 |     350 |
+----+---------+
(2 rows)

Downlod and extract this tarball, which includes three files that work together:

File Description
hibernate.cfg.xml This file specifies how to connect to the database and that the database schema will be deleted and recreated each time the app is run. It must be in the src/main/resources directory.
Sample.java This file uses the Hibernate ORM to map Java-specific objects to SQL operations. It must be in the src/main/java/com/cockroachlabs/ directory.
build.gradle This is the file you run to execute your app.

For more insight into this sample application, review the Sample.java file, which uses the Hibernate ORM to map Java-specific objects to SQL operations. Specifically, an accounts table gets created based on the Account class, session.save(new Account()) inserts rows into the table, and the CriteriaQuery<Account> query object defines the SQL query for selecting from the table so that balances can be printed.

package com.cockroachlabs;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.criteria.CriteriaQuery;

public class Sample {
    // Create a SessionFactory based on our hibernate.cfg.xml configuration
    // file, which defines how to connect to the database.
    private static final SessionFactory sessionFactory =
            new Configuration()
                    .configure("hibernate.cfg.xml")
                    .addAnnotatedClass(Account.class)
                    .buildSessionFactory();

    // Account is our model, which corresponds to the "accounts" database table.
    @Entity
    @Table(name="accounts")
    public static class Account {
        @Id
        @Column(name="id")
        public long id;

        @Column(name="balance")
        public long balance;

        // Convenience constructor.
        public Account(int id, int balance) {
            this.id = id;
            this.balance = balance;
        }

        // Hibernate needs a default (no-arg) constructor to create model objects.
        public Account() {}
    }

    public static void main(String[] args) throws Exception {
        Session session = sessionFactory.openSession();

        try {
            // Insert two rows into the "accounts" table.
            session.beginTransaction();
            session.save(new Account(1, 1000));
            session.save(new Account(2, 250));
            session.getTransaction().commit();

            // Print out the balances.
            CriteriaQuery<Account> query = session.getCriteriaBuilder().createQuery(Account.class);
            query.select(query.from(Account.class));
            for (Account account : session.createQuery(query).getResultList()) {
                System.out.printf("%d %d\n", account.id, account.balance);
            }
        } finally {
            session.close();
            sessionFactory.close();
        }
    }
}

Then in the hibernate-basic-sample directory, run the gradle file to fetch the dependencies in Sample.java (including Hibernate) and run the application:

$ gradle run 

Toward the end of the output, you should see:

1 1000
2 250

To verify that the table and rows were created successfully, you can again use the built-in SQL client:

$ cockroach sql -e 'SHOW TABLES' --database=bank
+----------+
|  Table   |
+----------+
| accounts |
+----------+
(1 row)
$ cockroach sql -e 'SELECT id, balance FROM accounts' --database=bank
+----+---------+
| id | balance |
+----+---------+
|  1 |    1000 |
|  2 |     250 |
+----+---------+
(2 rows)

What’s Next?

Read more about using the Java jdbc driver.

Read more about using the Hibernate ORM.

You might also be interested in using a local cluster to explore the following core CockroachDB features:



Yes No