eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Files such as images, audio, video, documents, etc. can be stored in a database as Binary Large Object (BLOB). A BLOB is a SQL data type that can store large binary data as a single entity.

In this tutorial, we’ll learn how to store and retrieve BLOB data using Java Database Connectivity (JDBC) with an H2 in-memory database.

2. Example Setup

To begin, let’s add the h2 dependency to the pom.xml:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.2.224</version>
</dependency>

Next, let’s create a schema named warehouses:

String sql = """
    CREATE TABLE IF NOT EXISTS warehouses (
    id INTEGER PRIMARY KEY,
    name text NOT NULL,
    capacity REAL,
    picture BLOB
);""";

Here, we create a table named warehouses with four columns. The fourth column is of type BLOB, which is suitable for saving binary objects like pictures, PDF files, etc.

Also, let’s set up the JDBC connection:

static Connection connect() throws SQLException {
    Connection connection = DriverManager.getConnection("jdbc:h2:./test", "sa", "");
    return connection;
}

In this method, we create a Connection object to establish a connection with the database.

Finally, let’s initiate a create operation to create a table in the database:

try (Connection connection = connect(); Statement stmt = connection.createStatement()) {
    stmt.execute(sql);
}

In the code above, we execute our SQL query to create a table.

 3. Saving  a File as BLOB

We can store file content in the database by first converting it into a byte array and then inserting it or streaming the file content in chunks.

3.1. Converting File to a Byte Array

If we intend to store a small file, converting it to a byte array may be an efficient choice. However, this approach may not be suitable for huge files.

First, let’s write a method to convert a file to a byte array:

static byte[] convertFileToByteArray(String filePath) throws IOException {
    File file = new File(filePath);
    try (FileInputStream fileInputStream = new FileInputStream(file); 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        for (int len; (len = fileInputStream.read(buffer)) != -1; ) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        return byteArrayOutputStream.toByteArray();
    }
}

The method above accepts the file path as an argument which is passed to the File object. Next, we create FileInputStream and ByteArrayOutputStream objects to read the file and store bytes read from the file respectively.

Also, we read the file in chunks of 1024 bytes at a time. If the fileInputStream returns -1, the end of the file is reached.

Next, let’s insert a new record into the warehouses table:

boolean insertFile(int id, String name, int capacity, String picture) throws SQLException, IOException {
    String insertSql = """
        INSERT INTO warehouses(id,name,capacity,picture) VALUES(?,?,?,?)
        """;
    try (Connection conn = connect()) {
        if (conn != null) {
            PreparedStatement stmt = conn.prepareStatement(insertSql);
            stmt.setInt(1, id);
            stmt.setString(2, name);
            stmt.setDouble(3, capacity);
            stmt.setBytes(4, convertFileToByteArray(picture));
            stmt.executeUpdate();
            return true;
        }
    }
    return false;
}

Here, we establish a connection to the database and create a PreparedStatement object to set values for each column. The file is converted to a byte array and set as a BLOB data using the setBytes() method.

Let’s see a unit test to demonstrate inserting a new record using the insertFile() method:

@ParameterizedTest
@CsvSource({ "1, 'Liu', 3000", "2, 'Walmart', 5000" })
void givenBlobFile_whenInsertingTheBlobFileAsByteArray_thenSuccessful(
    int id, 
    String name, 
    int capacity
) throws SQLException, IOException {
    boolean result = jdbcConnection.insertFile(id, name, capacity, TEST_FILE_PATH);
    assertTrue(result);
}

In the code above, we add two new records to the warehouses table. Finally, we assert that the operation returns true.

3.2. Saving the File as a Stream

When dealing with large files, converting the entire file to a byte array before saving it to the database may not be efficient. In such cases, we can save the file in chunks using a streaming approach.

Here’s an example that saves a file into the database in chunks:

boolean insertFileAsStream(
    int id, 
    String name, 
    int capacity, 
    String filePath
) throws SQLException, IOException {
    String insertSql = """
        INSERT INTO warehouses(id,name,capacity,picture) VALUES(?,?,?,?)
        """;
    try (Connection conn = connect()) {
        if (conn != null) {
            PreparedStatement stmt = conn.prepareStatement(insertSql);
            stmt.setInt(1, id);
            stmt.setString(2, name);
            stmt.setDouble(3, capacity);
            File file = new File(filePath);
            try (FileInputStream fis = new FileInputStream(file)) {
                stmt.setBinaryStream(4, fis, file.length());
                stmt.executeUpdate();
                return true;
            }
        }
    }
    return false;
}

In the code above, instead of converting the picture file to a byte array, we pass it to the FileInputStream object to stream the file contents directly into the database without loading the entire file into memory. This is more efficient for large files because it reduces OutOfMemoryErrors.

4. Retrieving a BLOB from a Database

Next, let’s look at how we can read binary data from the database as an input stream and write it directly to a file output stream.

Here’s a method that retrieves a record with BLOB data from the database:

static boolean writeBlobToFile(
    String query, 
    int paramIndex, 
    int id, 
    String filePath
) throws IOException, SQLException {
    try (
        Connection connection = connect(); 
        PreparedStatement statement = connection.prepareStatement(query)
    ) {
        statement.setInt(paramIndex, id);
        try (
            ResultSet resultSet = statement.executeQuery(); 
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath))
        ) {
            while (resultSet.next()) {
                InputStream input = resultSet.getBinaryStream("picture");
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
            }
            return true;
        }
    }
}

In the code above, we retrieve a BLOB from the database and write it to a file. Also, we create a PreparedStatement object to execute a query, retrieve the BLOB as a binary stream from the ResultSet, and read each byte in chunks of 1024 bytes.

Then, we ensure the read operation returns the number of bytes read, which may be less than the buffer size.

5. Conclusion

In this article, we learned how to write binary files into the database as a byte array. We also saw how to write a large file using a stream. Furthermore, we learned how to retrieve a blob file from the database and write it to a file.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)