Working with Databases in Java: PostgreSQL and MongoDB in Practice

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Should a Java Developer Know PostgreSQL and MongoDB?

Modern Java development rarely goes without interacting with databases. The two most popular systems — the relational PostgreSQL and the document-oriented MongoDB — cover 90% of enterprise application tasks. PostgreSQL is ideal for strict schemas and transactional systems, while MongoDB is suitable for flexible data structures and high write loads.

In this article, we will go through practical examples of connecting both databases from Java, perform basic CRUD operations, and compare the approaches. The material will be useful for both beginners and experienced developers who want to refresh their knowledge.



1. PostgreSQL in Java: The Classic of Relational Databases

1.1. Connection and Setup

To work with PostgreSQL in Java, the driver org.postgresql:postgresql is used. Add the dependency to pom.xml (Maven):

<dependency>    <groupId>org.postgresql</groupId>    <artifactId>postgresql</artifactId>    <version>42.7.1</version></dependency>

Connecting via JDBC looks like this:

String url = "jdbc:postgresql://localhost:5432/mydb";String user = "postgres";String password = "secret";

try (Connection conn = DriverManager.getConnection(url, user, password)) { System.out.println("Connection to PostgreSQL established!");} catch (SQLException e) { e.printStackTrace();}


1.2. CRUD Operations in Practice

Let's create a users table and perform basic operations:

// Creating a tableString createSQL = """    CREATE TABLE IF NOT EXISTS users (        id SERIAL PRIMARY KEY,        name VARCHAR(100),        email VARCHAR(100) UNIQUE,        age INTEGER    )""";

try (Statement stmt = conn.createStatement()) { stmt.execute(createSQL); System.out.println("Table created");}

// INSERTString insertSQL = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) { pstmt.setString(1, "Ivan Petrov"); pstmt.setString(2, "ivan@example.com"); pstmt.setInt(3, 30); pstmt.executeUpdate();}

// SELECTString selectSQL = "SELECT * FROM users WHERE age > ?";try (PreparedStatement pstmt = conn.prepareStatement(selectSQL)) { pstmt.setInt(1, 25); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.printf("ID: %d, Name: %s, Email: %s%n", rs.getInt("id"), rs.getString("name"), rs.getString("email")); }}

Important: Always use PreparedStatement to protect against SQL injection.



2. MongoDB in Java: Flexibility of the Document Model

2.1. Connection via MongoDB Sync Driver

Add to pom.xml:

<dependency>    <groupId>org.mongodb</groupId>    <artifactId>mongodb-driver-sync</artifactId>    <version>4.11.1</version></dependency>

Connecting to a local MongoDB:

import com.mongodb.client.MongoClients;import com.mongodb.client.MongoClient;import com.mongodb.client.MongoDatabase;

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");MongoDatabase database = mongoClient.getDatabase("mydb");System.out.println("Connection to MongoDB established");


2.2. CRUD Operations with Documents

Working with the users collection:

import com.mongodb.client.MongoCollection;import org.bson.Document;import static com.mongodb.client.model.Filters.*;

MongoCollection<Document> collection = database.getCollection("users");

// CREATE — inserting a documentDocument user = new Document("name", "Anna Smith

Blogs

Book Recommendations