Working with Databases in Java: PostgreSQL and MongoDB

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 to Working with Databases in Java



Modern Java development rarely goes without interaction with data storage systems. The choice between relational (SQL) and non-relational (NoSQL) databases is one of the key architectural tasks. In this article, using PostgreSQL (a classic relational DBMS) and MongoDB (a document-oriented NoSQL) as examples, we will analyze the main approaches, best practices, and provide ready-made code examples. The material will be useful for both beginners and experienced developers who want to systematize their knowledge.



1. Connecting to and Working with PostgreSQL in Java



1.1 Setting up the JDBC Driver



PostgreSQL is one of the most popular relational databases. The JDBC driver is used to work with it from Java. Add the dependency to pom.xml (Maven):



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


After adding the driver, you can establish a connection:



import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;

public class PostgresConnection { public static void main(String[] args) { String url = "jdbc:postgresql://localhost:5432/mydb"; String user = "admin"; 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 (Create, Read, Update, Delete)



Let's look at an example of working with the users table. Creating a record:



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


Reading data:



String selectSQL = "SELECT * FROM users WHERE id = ?";try (PreparedStatement pstmt = conn.prepareStatement(selectSQL)) {    pstmt.setInt(1, 1);    ResultSet rs = pstmt.executeQuery();    while (rs.next()) {        System.out.println(rs.getString("name") + " - " + rs.getString("email"));    }}


Updating and deleting are performed similarly via UPDATE and DELETE using PreparedStatement. Always use parameterized queries — this protects against SQL injections.



1.3 Using a Connection Pool (HikariCP)



In production, it is not recommended to open a new connection for each request. Use a connection pool. Add the dependency:



<dependency>    <groupId>com.zaxxer</groupId>    <artifactId>HikariCP</artifactId>    <version>5.0.1</version></dependency>


Configuration:



HikariConfig config = new HikariConfig();config.setJdbcUrl("jdbc:postgresql://localhost:5432/mydb");config.setUsername("admin");config.setPassword("secret");config.setMaximumPoolSize(10);

HikariDataSource ds = new HikariDataSource(config);Connection conn = ds.getConnection();


2. Connecting to and Working with MongoDB in Java



2.1 Setting up the MongoDB Java Driver



MongoDB stores data in JSON-like documents. The official driver is used for working with it. Maven dependency:



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


Connecting to a local database:





                
                

Blogs

Book Recommendations