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

When working with relational databases, we often need to store binary large objects (BLOBs), such as documents, images, and other media. Spring’s JdbcTemplate provides a lightweight, flexible API for performing these operations without the complexity of full ORM solutions.

In this tutorial, we’ll explore several practical approaches for inserting BLOB data using JdbcTemplate.

2. Introduction to the Problem

Storing binary data in a relational database is straightforward with the right JDBC APIs.

However, depending on file size, database vendor, and driver specifics, the insertion strategy can vary. For small or medium BLOBs, setting a byte array directly is enough. For large content, using a stream is more memory-efficient. And in some scenarios, we may need Spring’s SqlLobValue and LobHandler. In addition, we can use Spring’s SqlBinaryValue to solve the problem.

As always, we’ll explore these approaches by example. So, let’s first set up an in-memory H2 database in a Spring Boot application. Then, we’ll walk through each option using simple, focused JUnit test cases.

For simplicity, we’ll skip the database and Spring configurations in this tutorial.

So now, let’s create a SQL script create-document-table.sql containing the table creation statement:

CREATE TABLE DOCUMENT
(
    ID INT PRIMARY KEY,
    FILENAME   VARCHAR(255) NOT NULL,
    DATA       BLOB
);

As we can see, in the DOCUMENT table, the column DATA’s type is BLOB. We’ll use the DOCUMENT table throughout our examples.

To keep our test environment clean, we also define a matching teardown script drop-document-table.sql:

DROP TABLE DOCUMENT;

We’ll use these two scripts in @Sql annotations:

@Sql(value = "/com/baeldung/spring/jdbc/blob/create-document-table.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(value = "/com/baeldung/spring/jdbc/blob/drop-document-table.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@SpringBootTest(classes = InsertBlobUsingJdbcTemplateApplication.class)
@TestPropertySource(locations = { "classpath:com/baeldung/spring/jdbc/blob/application.properties" })
class InsertBlobUsingJdbcTemplateUnitTest {
    @Autowired
    private JdbcTemlate jdbcTemplate;
    private static final String CONTENT = "I am a very very long content.";
}

As the code shows, we put two @Sql annotations on our test class. By running our table-creation script before each test method and the drop script afterward, we ensure every test starts with a predictable, clean database schema. This keeps the test environment fully isolated and repeatable.

Also, we create the CONTENT constant to simulate the content of a file. Later, we’ll use a different approach to insert CONTENT’s value into the DOCUMENT table’s DATA column.

3. Using a byte Array

The first and most straightforward approach is to use PreparedStatement.setBytes(). In this method, we convert our content into a byte[] and directly store it in the database. This technique is ideal when the size of the BLOB is small enough to comfortably fit into memory.

Next, let’s see how it works:

byte[] bytes = CONTENT.getBytes(StandardCharsets.UTF_8);

jdbcTemplate.update(
  "INSERT INTO DOCUMENT (ID, FILENAME, DATA) VALUES (?, ?, ?)",
  1,
  "bigfile.txt",
  bytes
);

byte[] stored = jdbcTemplate.queryForObject("SELECT DATA FROM DOCUMENT WHERE ID = 1", (rs, rowNum) -> rs.getBytes("data"));
assertEquals(CONTENT, new String(stored, StandardCharsets.UTF_8));

Because we pass the entire byte array at once, the database driver doesn’t need to stream the data. Instead, it simply writes the full array to the BLOB column. This results in minimal boilerplate code and works reliably across all major JDBC drivers.

As we can see, this approach is straightforward, highly readable, and suitable for many use cases, such as short text documents, small images, or any binary data under a few megabytes.

4. Using an InputStream

The second approach involves using a binary stream instead of loading all the bytes into memory. With PreparedStatement.setBinaryStream(), we hand over an InputStream to the JDBC driver, which then streams the data directly into the BLOB field.

This technique is especially useful when:

  • The file is large (for example, tens or hundreds of megabytes)
  • The content originates as a stream (for instance, file uploads, network streams, memory-efficient pipelines)
  • We want to avoid high memory consumption

Next, let’s see this approach in action:

InputStream stream = new ByteArrayInputStream(CONTENT.getBytes(StandardCharsets.UTF_8));

jdbcTemplate.update(
  "INSERT INTO DOCUMENT (ID, FILENAME, DATA) VALUES (?, ?, ?)",
  2,
  "bigfile.txt",
  stream
);

byte[] stored = jdbcTemplate.queryForObject("SELECT DATA FROM DOCUMENT WHERE ID = 2", (rs, rowNum) -> rs.getBytes("data"));
assertEquals(CONTENT, new String(stored, StandardCharsets.UTF_8));

Our test simulates this by creating an InputStream over the content and passing it to the insert operation.

Streaming is more scalable because it prevents our application from holding large arrays in memory. Instead, we pass the stream and let the database driver manage the read-and-write operations incrementally.

This option is handy when the data source itself is already a stream, for example, files uploaded via REST endpoints.

5. Using Spring’s SqlLobValue and LobHandler (Deprecated in Spring 6.2)

Before Spring 6.2, another way to insert BLOB data in a database was to use SqlLobValue together with a LobHandler. Spring has provided different LobHandler implementations, most commonly DefaultLobHandler, to abstract vendor-specific LOB operations.

Although this approach still works, both SqlLobValue and LobHandler are now deprecated in Spring 6.2, replaced by the newer SqlBinaryValue API. Still, many existing Spring applications use this pattern, and it remains useful to understand. By the way, we’ll explore the SqlBinaryValue approach later.

Next, let’s see an example of how SqlLobValue and LobHandler do the job:

byte[] bytes = CONTENT.getBytes(StandardCharsets.UTF_8);

jdbcTemplate.update(
  "INSERT INTO DOCUMENT (ID, FILENAME, DATA) VALUES (?, ?, ?)",
  new Object[] { 3, "bigfile.txt", new SqlLobValue(bytes, new DefaultLobHandler()) },
  new int[] { Types.INTEGER, Types.VARCHAR, Types.BLOB }
);

byte[] stored = jdbcTemplate.queryForObject("SELECT DATA FROM DOCUMENT WHERE ID = 3", (rs, rowNum) -> rs.getBytes("DATA"));
assertEquals(CONTENT, new String(stored, StandardCharsets.UTF_8));

In the example, we pass a SqlLobValue instance as the parameter and supply the SQL types separately.

6. Using Spring’s SqlBinaryValue

Since Spring 6.2, using SqlBinaryValue to insert binary data is preferred over the deprecated SqlLobValue / LobHandler APIs.

SqlBinaryValue integrates directly with Spring’s JDBC parameter framework, meaning we wrap it inside a SqlParameterValue along with the appropriate SQL type:

byte[] bytes = CONTENT.getBytes(StandardCharsets.UTF_8);

jdbcTemplate.update(
  "INSERT INTO DOCUMENT (ID, FILENAME, DATA) VALUES (?, ?, ?)",
  4,
  "bigfile.txt",
  new SqlParameterValue(Types.BLOB, new SqlBinaryValue(bytes))
);

byte[] stored = jdbcTemplate.queryForObject("SELECT DATA FROM DOCUMENT WHERE ID = 4", (rs, rowNum) -> rs.getBytes("DATA"));
assertEquals(CONTENT, new String(stored, StandardCharsets.UTF_8));

In this example, SqlBinaryValue wraps the raw byte[] and provides the driver with a clean binary representation. We additionally wrap it in SqlParameterValue, which lets us specify the JDBC type (Types.BLOB).

7. Conclusion

In this article, we explored different practical techniques for inserting BLOB data using Spring’s JdbcTemplate. By walking through focused JUnit test cases, we demonstrated how each approach works in isolation.

By understanding these options, we can choose the right strategy for our specific database and application requirements.

As always, the complete source code for the examples is available over on GitHub.

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)