Join our community of software engineering leaders and aspirational developers. Always
stay in-the-know by getting the most important news and exclusive content delivered
fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter
in the past. Click the button below to open the re-subscribe form
in a new tab. When you're done, simply close that tab and continue
with this form to complete your subscription.
The New Stack does not sell your information or share it with
unaffiliated third parties. By continuing, you agree to our
Terms of Use and
Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!
We’re so glad you’re here. You can expect all the best TNS content to arrive
Monday through Friday to keep you on top of the news and at the top of your game.
What’s next?
Check your inbox for a confirmation email where you can adjust your preferences
and even join additional groups.
Follow TNS on your favorite social media networks.
For developers working with Java, connecting to the right database can provide significant benefits to their organization, while also making their jobs easier in the long term. This is especially true for databases that combine the flexibility and agility of NoSQL with the familiarity of SQL.
In this article, I’ll briefly dive into the NoSQL database landscape, as well as walk you through the structure of a simple Java example that interacts with a NoSQL database.
NoSQL databases store data as JSON documents rather than relational tables with columns and rows. Some NoSQL databases provide programming interfaces in both SQL and native document APIs. Types of NoSQL databases include document databases, key-value stores, wide-column databases and graph databases.
NoSQL databases are known to store and process vast amounts of data efficiently and have become a foundational technology for many modern businesses. Many NoSQL databases are available in the cloud as a fully managed Database as a Service (DBaaS) or for on-premises installations. SDKs in various programming languages and APIs are used by developers to interact with such databases.
Before we get into the code samples, it would be helpful to look at the sample data and how it’s organized within the database, often referred to as the data model.
Data Model
At the highest level of data organization, this database contains one or more buckets. Each bucket can contain one or more scopes, and each scope can contain one or more collections. Within collections are JSON documents.
This hierarchy is similar to the relational database where databases have schemas, tables and rows, etc. This hierarchical data container model of this document database maps very well to the relational model: bucket = database, scope = schema, collection = table, document = row.
This mapping allows you to access data either through the document data model in collections or the relational model using SQL.
Couchbase delivers Capella, the cloud database platform for modern applications. Capella enables developers and architects to quickly build the apps of the future and deliver always-on experiences to customers, on a mission to simplify how businesses develop, deploy and consume modern applications.
Learn More
The latest from Couchbase
The sample in this example is called “Travel Sample,” a data set for an airline travel information system.
The document (JSON) data model for the Travel Sample data set is shown below.
The major entities are airline, airport, route, linking airline and airport and hotel as a separate entity.
The diagram below shows the relationship between the various documents in the Airline Travel system. It shows the primary key, ID and type fields that each document contains, with additional representative fields in each type of document.
Now we are ready to look at some basic data access operations on this sample dataset.
Code Examples
Now that the basic concepts are covered, let us see how to connect to the database, establish a context for a bucket and collection to work on, perform simple key-value operations and queries, and finally modify some data in the database.
Connect to the Database Cluster
A connection string typically consists of a host URL (IP name/addresses), followed by a username and password. Using this connection string, you can get a connection object to the database cluster. In this example, we are using localhost (127.0.0.1) as the database host. You may want to replace the DB name, username and password that are appropriate to your database cluster. A connection to the database cluster is represented by a cluster object.
class Program {
public static void main(String[] args) {
var cluster = Cluster.connect(
"dbName", "username", "password"
);
Set Context to the Appropriate Collection
Let us now establish a context for a very specific dataset: a bucket named “travel-sample” that already contains the Travel Sample data set collection. The code below sets our current context to the default collection within the “travel-sample.”
var bucket = cluster.bucket("travel-sample");
var collection = bucket.defaultCollection();
Basic Key-Value Operation (Get a Document)
The key value (KV) or data service offers the simplest way to retrieve or mutate data where the key is known. The get method below retrieves specific data (value) associated with a key. In this case, the key is “airline_10.”
try {
var result = collection.get("airline_10");
System.out.println(result.toString());
}
catch (DocumentNotFoundException ex) {
System.out.println("Document not found!");
}
}
}
Query Rows Using SQL
Here is a snippet of code performing a SQL query to retrieve hotel names in the city of Malibu from the Travel Sample data set.
Query methods can have named or positional parameters.
Below is a named parameter example:
The code proceeds to access the travel-sample database (specifically the name, city and state buckets). The queryOptions() method allows the customization of various SQL query options.
Subdocuments are parts of the document that you can atomically and efficiently update and retrieve.
In the code below, the lookupIn operation queries the “airport_1254” document for a certain path (here, it’s the geo.alt path). This code allows us to retrieve the document path using the `subdoc get` operation: (get("geo.alt")).
try {
LookupInResult result = collection.lookupIn(
"airport_1254",
Collections.singletonList(get("geo.alt"))
);
var str = result.contentAs(0, String.class);
System.out.println("Altitude = " + str);
} catch (DocumentNotFoundException ex) {
System.out.println("Document not found!");
}
}
}
Using Subdocument Mutate Operations
Mutation operations modify one or more paths in the document. In the code below, the mutateIn operation is used to modify the airline_10 by using a full doc-level upsert, which will create the value of an existing path with parameters (country, Canada).
Upsert is used to insert a new record or update an existing one. If the document doesn’t exist, it will be created. Upsert is a combination of insert and update.
The .put method allows the user to insert a mapping into a map. If an existing key is passed, the new value replaces the previous value.
The sample data set and code examples used above are from the distributed NoSQL cloud database Couchbase. Speaking of Databases as a Service, check out Couchbase Capella to see how modern enterprises are able to deliver flexibility across various use cases with built-in multimodel and mobile synchronization capabilities, and drive millisecond data response at scale.
These and many more examples can be found and run from Couchbase Playground. To connect with other like-minded developers in the community for more inspiration, check out the Couchbase Forums. For those just getting started with Java, another great resource to consider is the free online Java developer certification course offered by Couchbase Academy.
Couchbase delivers Capella, the cloud database platform for modern applications. Capella enables developers and architects to quickly build the apps of the future and deliver always-on experiences to customers, on a mission to simplify how businesses develop, deploy and consume modern applications.