Home Java javaTutorial Spring Data JPA Stream Query Methods

Spring Data JPA Stream Query Methods

Nov 22, 2024 am 05:35 AM

Spring Data JPA Stream Query Methods

Introduction

Traditionally, fetching large amounts of data can strain memory resources, as it often involves loading the entire result set into memory.

=> Stream query methods offer a solution by providing a way to process data incrementally using Java 8 Streams. This ensures that only a portion of the data is held in memory at any time, enhancing performance and scalability.

In this blog post, we'll dive deep into how stream query methods work in Spring Data JPA, explore their use cases, and demonstrate their implementation.

For this guide, we’re using:

  • IDE: IntelliJ IDEA (recommended for Spring applications) or Eclipse
  • Java Version: 17
  • Spring Data JPA Version: 2.7.x or higher (compatible with Spring Boot 3.x)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Copy after login
Copy after login

NOTE: For more detailed examples, please visit my GitHub repository here

1. What are Stream Query Methods?

Stream query methods in Spring Data JPA allow us to return query results as a Stream instead of a List or other collection types. This approach provides several benefits:

  • Efficient Resource Management: Data is processed incrementally, reducing memory overhead.

  • Lazy Processing: Results are fetched and processed on-demand, which is ideal for scenarios like pagination or batch processing.

  • Integration with Functional Programming: Streams fit with Java's functional programming features, enabling operations like filter, map, and collect.

2. How To Use Stream Query Methods?

=> Let's imagine that we are developing an e-commerce application and want to:

  • Retrieve all customers who placed orders after a specific date.
  • Filter orders with a total amount above a specific provided amount.
  • Group customers by their total order value within the last 6 months.
  • Return the data as a summary of customer names and their total order values.

Entities

  • Customer: Represents a customer.
@Setter
@Getter
@Entity
@Entity(name = "tbl_customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Order> orders;
}
Copy after login
Copy after login
  • Order: Represents an order placed by a customer.
@Setter
@Getter
@Entity(name = "tbl_order")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Double amount;
    private LocalDateTime orderDate;

    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;
}
Copy after login
Copy after login

Repository

  • CustomerRepository used for selecting customers and their associated orders placed after a specific date. And we used Stream instead of List to handle result of query.
public interface CustomerRepository extends JpaRepository<Customer, Long> {
    @Query("""
                SELECT c FROM tbl_customer c JOIN FETCH c.orders o WHERE o.orderDate >= :startDate
            """)
    @QueryHints(
            @QueryHint(name = AvailableHints.HINT_FETCH_SIZE, value = "25")
    )
    Stream<Customer> findCustomerWithOrders(@Param("startDate") LocalDateTime startDate);
}
Copy after login
Copy after login

NOTE:

  • The JOIN FETCH ensures orders are eagerly loaded.

  • The @QueryHints used to provide additional hints to the JPA provides (e.g,. Hibernate) to optimize the query execution.

=> For example, when my query return 100 records:

  • The first 25 records are fetched and processed by the application.
  • Once those are processed, the next 25 are fetched, and so on, until all 100 records are processed.
  • This behavior minimizes memory usage and avoids loading all 100 records into memory at once.

Service

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Copy after login
Copy after login

Here's the service class to process the data with two parameters startDate and minOrderAmount. As you can see, we don't filter by using sql query and load all data as stream then filter and group by our Java code.

Controller

@Setter
@Getter
@Entity
@Entity(name = "tbl_customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Order> orders;
}
Copy after login
Copy after login

Testing

=> To create data for testing, you can execute the following script inside my source code or add by yourself.

src/main/resources/dummy-data.sql

Request:

  • startDate: 2024-05-01T00:00:00
  • minOrderAmount: 100
@Setter
@Getter
@Entity(name = "tbl_order")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Double amount;
    private LocalDateTime orderDate;

    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;
}
Copy after login
Copy after login

Response:

  • Return all customers with their total amount which equal or greater than minOrderAmount.
public interface CustomerRepository extends JpaRepository<Customer, Long> {
    @Query("""
                SELECT c FROM tbl_customer c JOIN FETCH c.orders o WHERE o.orderDate >= :startDate
            """)
    @QueryHints(
            @QueryHint(name = AvailableHints.HINT_FETCH_SIZE, value = "25")
    )
    Stream<Customer> findCustomerWithOrders(@Param("startDate") LocalDateTime startDate);
}
Copy after login
Copy after login

3. Stream vs List

=> You can use IntelliJ Profiler to monitor memory usage and execution time. For more detail about how to add and test with large data set, you can find in my GitHub repository

Small Dataset: (10 customers, 100 orders)

  • Stream: Execution time (~5ms), Memory usage (Low)
  • List: Execution time (~4ms), Memory usage (Low)

Large Dataset (10.000 customers, 100.000 orders)

  • Stream: Execution time (~202ms), Memory usage (Moderate)
  • List: Execution time (~176ms), Memory usage (High)

Performance Metrics

Metric Stream List
Initial Fetch Time Slightly slower (due to lazy loading) Faster (all at once)
Memory Consumption Low (incremental processing) High (entire dataset in memory)
Memory Consumption Low (incremental processing) High (entire dataset in memory)
Processing Overhead Efficient for large datasets May cause memory issues for large datasets
Batch Fetching Supported (with fetch size) Not applicable
Error Recovery Graceful with early termination Limited, as data is preloaded

Wrapping up

Spring Data JPA stream query methods offer an elegant way to process large datasets efficiently while leveraging the power of Java Streams. By processing data incrementally, they reduce memory consumption and integrate seamlessly with modern functional programming paradigms.

What are your thoughts on stream query methods? Share your experiences and use cases in the comments below!

See you in the next posts. Happy Coding!

The above is the detailed content of Spring Data JPA Stream Query Methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles