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.

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

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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

1. Introduction

Spring Data JPA provides a powerful abstraction layer for interacting with relational databases. However, traditional relational tables might not be ideal for storing complex, semi-structured data like product details or user preferences. This is where JSONB data types come in. In this tutorial, we’ll explore various approaches for querying JSONB columns using Spring Data JPA.

2. JSONB Columns

JSONB (JavaScript Object Notation for Databases) is a data type specifically designed for storing JSON data within relational databases like PostgreSQL. It allows us to represent complex data structures with key-value pairs and nested objects within a single column. In conjunction with the JPA provider (such as Hibernate), Spring Data JPA allows us to map these JSONB columns to attributes within our entity classes.

3. Mapping JSONB Columns

We can use the @Column annotation with the columnDefinition attribute to explicitly define the column type in the entity class:

@Column(columnDefinition = "jsonb")
private String attributes;

This approach is primarily relevant to PostgreSQL, which natively supports the jsonb data type. By adding this annotation to the corresponding attribute in our entity class, we provide a hint to the database about the desired column type. Spring Data JPA typically auto-detects the jsonb data type based on the database column definition, making this annotation optional in many cases.

4. Setting up Project Dependencies and Test Data

We’ll create a basic Spring Boot project with the necessary dependencies and test data for testing the JSONB queries.

4.1. Project Setup

First, we need to add the necessary dependencies to our Maven pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

4.2. Entity Class

Next, let’s create a Java class named Product to represent our entity:

public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Column(columnDefinition = "jsonb")
    private String attributes;

    // Getters and Setters 
}

This class defines the Product entity with idname, and attributes fields. The attributes field is a String that will hold the serialized JSON data for product details. We use @Column(columnDefinition = “jsonb”) to hint the database to create an attributes column as a JSONB type.

After defining the Product entity class, Hibernate will generate the following SQL when the application starts up and initializes the database schema:

CREATE TABLE Product (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    name VARCHAR(255),
    attributes JSONB
);

4.3. Prepare Test Data

Below is the SQL script that we use to prepare our database before running the test cases. We can save this script in a .sql file and place it inside the src/test/resources directory of our project:

DELETE FROM product;

INSERT INTO product (name, attributes)
VALUES ('Laptop', '{"color": "red", "size": "15 inch"}');

INSERT INTO product (name, attributes)
VALUES ('Phone', '{"color": "blue", "size": "6 inch"}');

INSERT INTO product (name, attributes)
VALUES ('Headphones', '{"brand": "Sony", "details": {"category": "electronics", "model": "WH-1000XM4"}}');

INSERT INTO product (name, attributes)
VALUES ('Laptop', '{"brand": "Dell", "details": {"category": "computers", "model": "XPS 13"}}');

Then, we use the @Sql annotation with the executionPhase attribute set to BEFORE_TEST_METHOD in the test class to insert test data into the database before each test method execution:

@Sql(scripts = "/testdata.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)

5. Using Native Queries with @Query

In this section, we’ll leverage native SQL queries with PostgreSQL JSONB operators to filter and retrieve data based on values within the JSONB column. We use the @Query annotation to define these native queries within our Spring Data JPA repository interface.

5.1. Querying with JSONB Operators

The @Query annotation allows us to define custom queries within our repository interface using native SQL syntax. This approach is particularly useful when working with JSONB columns, as it enables us to utilize PostgreSQL’s native JSONB operators directly within the query.

Let’s write a query using JSONB operators to find all products with a specific color value:

public interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT * FROM product WHERE attributes ->> ?1 = ?2", nativeQuery = true)
    List<Product> findByAttribute(String key, String value);
}

The findByAttribute() method takes in two arguments representing the key of the JSON attribute (such as “color”) and filters by a value indicating the desired value for that attribute. The @Query annotation defines a native SQL query that utilizes the ->> operator to access the key within the attributes JSONB column.

Then, the placeholders ?1 and ?2 in the query are replaced with the actual name of the key and value provided as method arguments during execution. Next, let’s create a test case to verify the functionality of the findByAttribute() method:

List<Product> redProducts = productRepository.findByAttribute("color", "red");

assertEquals(1, redProducts.size());
assertEquals("Laptop", redProducts.get(0).getName());

5.2. Querying Nested with JSONB Operators

We’re utilizing PostgreSQL’s -> and ->> operators to query nested JSONB data:

  • The -> operator is used to access a specific key within a JSONB object.
  • The ->> operator is used to access the value corresponding to a specific key within a JSONB object as text.

Let’s write another query for handling nested keys:

@Query(value = "SELECT * FROM product WHERE attributes -> ?1 ->> ?2 = ?3", nativeQuery = true)
List<Product> findByNestedAttribute(String key1, String key2, String value);

This query allows us to search for entities where a specific nested attribute matches a given value. For example, if we want to find products where the “details.category” is “electronics”, we’d call this method with “details”, “category”, and “electronics as parameters:

List<Product> electronicProducts = productRepository.findByNestedAttribute("details", "category", "electronics");

assertEquals(1, electronicProducts.size());
assertEquals("Headphones", electronicProducts.get(0).getName());

5.3. Querying with jsonb_extract_path_text Functions

We can also leverage the jsonb_extract_path_text function in our native SQL queries to extract specific values from JSONB data. jsonb_extract_path_text is a PostgreSQL function used to extract a specific value from a JSONB column based on a given path.

The jsonb_extract_path_text function returns the extracted value as text. If the specified path doesn’t exist in the JSONB structure, the function returns NULL.

Let’s see an example of using jsonb_extract_path_text:

public interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT * FROM product WHERE jsonb_extract_path_text(attributes, ?1) = ?2", nativeQuery = true)
    List<Product> findByJsonPath(String path, String value);
}

The findByJsonPath() method accepts two arguments. The first argument is the path string indicating the specific key within the JSONB object to extract. The second argument represents the expected value for the extracted attribute:

List<Product> redProducts = productRepository.findByJsonPath("color", "red");

assertEquals(1, redProducts.size());
assertEquals("Laptop", redProducts.get(0).getName());

5.4. Querying Nested with jsonb_extract_path_text Functions

Let’s see how we can adjust the query to handle nested keys using jsonb_extract_path_text functions:

@Query(value = "SELECT * FROM product WHERE jsonb_extract_path_text(attributes, ?1, ?2) = ?3", nativeQuery = true)
List<Product> findByNestedJsonPath(String key1, String key2, String value);

We provide key1 and key2 as path elements to traverse the nested JSONB structure:

List<Product> electronicProducts = productService.findByNestedJsonPath("details", "category", "electronics");

assertEquals(1, electronicProducts.size());
assertEquals("Headphones", electronicProducts.get(0).getName());

In this example, the findByNestedJsonPath(“details”, “category”, “electronics”) would target products where the nested “details.category” value is “electronics“.

6. Using Custom JPA Specification Approach

JPA Specifications are interfaces that encapsulate the criteria used for filtering data. They define what data needs to be retrieved based on specific conditions. This interface, provided by Spring Data JPA, allows repositories to implement custom query methods that accept a Specification<T> instance as an argument.

We can create a class that implements the Specification<T> interface. This class defines the toPredicate() method, which utilizes the CriteriaBuilder to construct the actual query predicate based on the provided criteria (key and value for filtering):

public class ProductSpecification implements Specification<Product> {
    private final String key;
    private final String value;

    public ProductSpecification(String key, String value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public Predicate toPredicate(Root root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        return cb.equal(
            cb.function("jsonb_extract_path_text", String.class, root.get("attributes"), cb.literal(key)),
            value
        );
    }
}

The toPredicate() method defines how the filtering predicate is constructed using the CriteriaBuilder provided as an argument. In this example, we’re assuming the key is located at the top level of the JSONB data.

To use this custom specification, the ProductRepository needs to extend JpaSpecificationExecutor<Product>:

public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
}

Here’s a basic example of a custom specification for filtering products based on attributes within the JSONB column:

ProductSpecification spec = new ProductSpecification("color", "red");
Page<Product> redProducts = productRepository.findAll(spec, Pageable.unpaged());

assertEquals(1, redProducts.getContent().size());
assertEquals("Laptop", redProducts.getContent().get(0).getName());

7. Conclusion

In this article, we explored various approaches for querying JSONB columns using Spring Data JPA. For basic filtering criteria, native SQL queries might offer a straightforward solution. However, the JPA specification provides a compelling alternative when dealing with complex filtering logic or the need for reusability.

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.

Course – LSD – NPI (cat=JPA)
announcement - icon

Get started with Spring Data JPA through the reference Learn Spring Data JPA:

>> CHECK OUT THE COURSE

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