Build a Java App with CockroachDB

On this page Carat arrow pointing down
Warning:
CockroachDB v1.1 is no longer supported as of April 12, 2019. For more details, refer to the Release Support Policy.

This tutorial shows you how build a simple Java application with CockroachDB using a PostgreSQL-compatible driver or ORM.

We have tested the Java jdbc driver and the Hibernate ORM enough to claim beta-level support, so those are featured here. If you encounter problems, please open an issue with details to help us make progress toward full support.

Tip:
For a more realistic use of Hibernate with CockroachDB, see our examples-orms repository.

Before You Begin

Make sure you have already installed CockroachDB.

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:

icon/buttons/copy
# On Mac:
$ brew install gradle
icon/buttons/copy
# On Ubuntu Linux:
$ apt-get install gradle

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

Step 2. Start a single-node cluster

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

icon/buttons/copy
$ cockroach start \
--insecure \
--store=hello-1 \
--host=localhost

Step 3. Create a user

In a new terminal, as the root user, use the cockroach user command to create a new user, maxroach.

icon/buttons/copy
$ cockroach user set maxroach --insecure

Step 4. Create a database and grant privileges

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

icon/buttons/copy
$ cockroach sql --insecure -e 'CREATE DATABASE bank'

Then grant privileges to the maxroach user.

icon/buttons/copy
$ cockroach sql --insecure -e 'GRANT ALL ON DATABASE bank TO maxroach'

Step 5. Run the Java code

Download 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.

icon/buttons/copy
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:

icon/buttons/copy
$ 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:

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

What's Next?

Read more about using the Hibernate ORM, or check out a more realistic implementation of Hibernate with CockroachDB in our examples-orms repository.

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


Yes No
On this page

Yes No