Java MongoDB Transactions: Creation, Management & Workflows Simplified | A 101 Guide

• July 30th, 2022

Java Mongodb Transactions | Hevo Data | Cover Image

Handling databases and performing several operations on the data can be challenging. Database management systems were introduced to solve the management and working problems of gathered data. One of the most popular databases is MongoDB. MongoDB is one of the most flexible databases, and running it with Java makes it even faster and easier.

In this article, you will learn about Java MongoDB transactions. And further, we will discuss how to create, manage, and work with MongoDB transactions.

Table of contents

  1. Prerequisites
  2. What is MongoDB?
  3. How to Run MongoDB With Java?
  4. What is MongoDB Transaction?
  5. Creation of Java MongoDB Transactions
  6. Management of Java MongoDB Transactions
  7. Workflow of Java MongoDB Transactions
  8. Conclusion

Prerequisites

Basic understanding of databases.

What is MongoDB?

Image source

MongoDB is a NoSQL database that is fundamentally different from SQL databases. MongoDB is a non-relational, open-source, platform-independent, and document-based database. SQL databases stores related data in tables, whereas MongoDB deals with non-related data.

MongoDB supports ACID (Atomicity, Consistency, Isolation, and Durability) transactions in single or multiple documents. These ACID properties of transactions ensure that complex transaction operations are safe and reliable, guaranteeing data validity. MongoDB introduced multiple documents, collections, and databases ACID transactions in MongoDB 4.0 version.

MongoDB runs on standard operating systems, Windows, Linux, macOS, and the cloud. The MongoDB edition that runs on the operating system is the MongoDB Community Server, and the MongoDB installation on the cloud is called MongoDB Atlas.

How to Run MongoDB with Java?

Get Java installed in your system and your preferred Integrated development environment (IDE) ready. To set up Java and MongoDB, first, you should get the MongoDB Java Driver. The resources for MongoDB installation will be picked up by two IDEs either in Gradle or Maven. MongoDB Java Drivers provide both synchronous and asynchronous interaction.

Steps to Get MongoDB Java Driver

  1. Install the proper version of the MongoDB driver from this website. Then, go to the products from the menu icon. Find the ‘Data Direct’ option and click on it.
Steps to Get MongoDB Java Driver
Image source
  1. You will get redirected to another webpage where you can find the ‘Data Connectivity’ option in the overview panel, under which you will see JDBC. Click on it.
Steps to Get MongoDB Java Driver
Image source
  1. Another page will open. Search for MongoDB from the list and click on it to move further.
Steps to Get MongoDB Java Driver
Image source
  1. A new page will appear, where you will see the Download option. Click on it, and then you will have two options; Windows and Linux. As per your OS system, click on it to download.
Steps to Get MongoDB Java Driver
Image source
  1. You have to fill up a form for download and click download.
  2. After downloading, extract your downloaded file.
  3. Open the extracted file to start the installation. Click on ‘Next’ to proceed.
  4. Accept all terms and conditions, then move forward by clicking next.
  5. Note: Do not change anything in the upcoming two windows. Click next to proceed.
Steps to Get MongoDB Java Driver
Image source
  1. Finally, you will reach to install option. Click on it, and the installation will start. 
  2. Wait for the installation process to complete. 
Steps to Get MongoDB Java Driver
Image source
  1. When the installation is complete, click on Done to finish the installation.
  2. Open your C drive and follow the below path. If you find a JDBC folder, the installation is successful.

Scale your data integration effortlessly with Hevo’s Fault-Tolerant No Code Data Pipeline

As the ability of businesses to collect data explodes, data teams have a crucial role in fueling data-driven decisions. Yet, they struggle to consolidate the scattered data in their warehouse to build a single source of truth. Broken pipelines, data quality issues, bugs and errors, and lack of control and visibility over the data flow make data integration a nightmare.

1000+ data teams rely on Hevo’s Data Pipeline Platform to integrate data from over 150+ sources in a matter of minutes. Billions of data events from sources as varied as SaaS apps, Databases, File Storage, and Streaming sources can be replicated in near real-time with Hevo’s fault-tolerant architecture. What’s more – Hevo puts complete control in the hands of data teams with intuitive dashboards for pipeline monitoring, auto-schema management, and custom ingestion/loading schedules. 

This, combined with transparent pricing and 24×7 support, makes us the most special data pipeline software on review sites.

Take our 14-day free trial to experience a better way to manage data pipelines.

Get started for Free with Hevo!

What is MongoDB Transaction?

Transaction in MongoDB is a logical group of processes that performs one or more operations across multiple documents. The transaction provides a way to group and isolate multiple statements and process them as a single operation.

Instead of executing a bunch of commands individually, you can use transactions to bundle together and execute the commands in a different context.

These operations in the transactions are the multiple read and write operations done to and from the MongoDB database. Transactions maintain the integrity of the set of operations and provide strong data consistency to the end user. 

The transactions in MongoDB have ACID properties. These properties ensure that the complex operations are safe and reliable. MongoDB supports multi-document and distributed multi-document. 

Creation of Java MongoDB Transactions

Transactions can only be performed on databases that run as a part of a large cluster. This cluster can either be a sharded database cluster or a replica set. Usually, MongoDB transactions are written and executed from external applications via API methods. Here, we’ll create a transaction using the MongoDB shell. 

Note: After the initial startTransaction() method, the operation will automatically abort if the transaction session runs for more than 60 seconds. 

Following are the steps to conceptualize a transaction session from beginning to end.

db.authors.find()
[
 {
   _id: ObjectId("620397dd4b871fc65c193106"),
   first_name: 'James',
   last_name: 'Joyce',
   title: 'Ulysses'
 },
 {
   _id: ObjectId("620398016ed0bb9e23785973"),
   first_name: 'William',
   last_name: 'Gibson',
   title: 'Neuromancer'
 },
 {
   _id: ObjectId("6203981d6ed0bb9e23785974"),
   first_name: 'George',
   last_name: 'Orwell',
   title: 'Homage to Catalonia'
 },
 {
   _id: ObjectId("620398516ed0bb9e23785975"),
   first_name: 'James',
   last_name: 'Baldwin',
   title: 'The Fire Next Time'
 }
]

Same with an API, you create a transaction session by using the code:

var session = db.getMongo().startSession()

The next step is to start the transaction by calling the startTransaction() method. Use the below command: 

session.startTransaction( 
    { "readConcern": { "level": "snapshot" },
      "writeConcern": { "w": "majority } 
     } 
)

There are two options for startTransaction() method: read concern and write concern.

The read concern set is ignored inside the transaction at the collection and database level. Therefore, you must set the transaction-level read concern at the startTransaction(). However, the read concern default sets to the session-level read concern for a transaction.

If both transaction-level and session-level read concern are not set, then the read concerns of client-level are set automatically. The client-level read concern is ‘local’ for reads against the primary. 

Write concern are used to commit the write operations. The write operations inside transactions must be issued implicitly by specifying write concern. The write operations are then committed using the transaction-level write concern. 

You can set the transaction-level write concern at startTransaction(). If the transaction-level write concern is not set, it defaults to the session-level write concern for the commit. If both transaction-level and session-level write concerns are unset, the transaction-level write concern automatically goes to the client-level write concern.

Management of Java MongoDB Transactions

Managing all the transactions can be hefty work, but here are a few ways to manage the transactions. You can add transaction support using Java Spring data and Java Mongo Drivers. A driver API does this:

try (ClientSession session = client.startSession()) {
    session.startTransaction();
    try {
        collection.insertOne(session, documentOne);
        collection.insertOne(session, documentTwo);
        session.commitTransaction();
    } catch (Exception e) {
        session.abortTransaction();
    }
}

The client sessions obtained from client.startSession() should be short-lived and released at once when no longer needed. Thus, ensure to include the close() command.

The above snippet contains the session (lsid) in each command line. ‘startTransaction’ is sent with the first command representing the transaction. And when completed, the transaction is committed by sending ‘commitTranscation.’

The previous versions of MongoDB did not support transactions, so the essential part is to configure the MongoTransactionManager in your ApplicationContext. Transaction Manager is an entry point for annotation-based transaction support. For configuration, use the below code:

@Configuration
class Config extends AbstractMongoConfiguration {
  @Bean
  MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
    return new MongoTransactionManager(dbFactory);
  }
}
@Service
class DocumentService {
  private final MongoOperations operations;
  DocumentService(MongoOperations operations) {
    this.operations = operations;
  }

  @Transactional
  void insertDocuments() {
    operations.insert(documentOne);
    operations.insert(documentTwo);
  }
}

That’s it. There is not much for managing Java MongoDB transactions, so there are a few simple steps to look into.

Workflow of Java MongoDB Transactions

At the first stage of using the transaction, you need to start a MongoDB session through a driver. This article follows a MongoDB session with the MongoDB Java driver. Then, use that session to execute your group of database operations. You can run any CRUD (create, read, update, and delete) operations across multiple documents, collections, and shards. 

MongoDB’s transactions have single-write-node origins, even in the context of a single shard. Its storage engine and replication protocol are replaced for the pathway for transactions. Given below is a figure representing an eCommerce app having 2 MongoDB clients.

Image source

Here, Client 1 performs transactions, and Client 2 reads a record updated by the transaction invoked by Client 1. Client 1 inserts a new order into the orders collection and updates the stock of the ordered item (assuming the order is shipped successfully). Now, the only write concern suitable for high data durability is the majority. The majority means most replicas, i.e., a majority of replicas, are to commit the changes before the primary recognizes the success of the write to the client.

The transaction will get blocked until at least one or two secondaries pull the update from the primary using replication. This process makes MongoDB’s single-shard transaction writes a bit slower than other transactional NoSQLs. 

Conclusion

We walked through using MongoDB in Java and the transaction’s creation, management, and workflow. Using Java MongoDB transactions in databases guarantees that a database will hold a consistent state after running a group of operations.

MongoDB has adopted the working of transactions from most familiar transactional patterns implemented in MySQL, Oracle, and other ACID relational databases. Ironically, the feature of MongoDB data modeling for related data to be stored together in a single document leverages the document model not requiring multi-document transactions. But developers admire the flexibility in modeling their data. Thus, there exists the function of transactions in MongoDB.

Visit our Website to Explore Hevo

Hevo Data, a No-code Data Pipeline, can seamlessly transfer data from a vast sea of 100+ sources such as MongoDB & MongoDB Atlas to a Data Warehouse or a Destination of your choice to be visualized in a BI Tool. It is a reliable, completely automated, and secure service that doesn’t require you to write any code!  

If you are using MongoDB as your NoSQL Database Management System and searching for a no-fuss alternative to Manual Data Integration, then Hevo can effortlessly automate this for you. Hevo, with its strong integration with 100+ sources & BI tools(Including 40+ Free Sources), allows you to not only export & load data but also transform & enrich your data & make it analysis-ready in a jiffy.

Want to take Hevo for a ride? Sign Up for a 14-day free trial and simplify your Data Integration process. Check out the pricing details to understand which plan fulfills all your business needs.

Tell us about your experience of learning about the Java MongoDB Transaction! Share your thoughts with us in the comments section below.

No-code Data Pipeline for MongoDB