In previous articles, we saw how to use Vavr List and Option with Hibernate Now, let’s see how to use Vavr List and Option data types with Spring JPA Repository. The goal is to be able to write this:

import com.demo.model.Customer;
import io.vavr.collection.List;
import io.vavr.control.Option;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
    List<Customer> findAllByCity(String city);
    Option<Customer> findByName(String name);

Thanks to this Vavr List, you can enjoy concise functional code in your app. You can for instance use the methods List.map(), List.flatMap() or List.filter() without the whole .stream() and .collect() boilerplate code.

To do this, we just need to override some Spring JPA functions. First, add this dependency to your pom.xml:

<dependency>
    <groupId>io.github.jleblanc64</groupId>
    <artifactId>lib-custom</artifactId>
    <version>1.0.7</version>
</dependency>

A good place to load the custom code is in the Spring config function:

import io.github.jleblanc64.libcustom.LibCustom;
import io.github.jleblanc64.libcustom.custom.spring.VavrHibernate6;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;

@Bean
public DataSource getDataSource() {
    VavrHibernate6.override();
    LibCustom.load();
    (...)

Indeed this code is executed before the persistence layer instantiation. You can find the whole DataSourceConfig code in Github.

You can see a full working Spring Boot app that uses these strategies in my Github repo. You may leave a question in the issues if you need.


<
Previous Post
Use Vavr List and Option with Spring 6 DTOs
>
Next Post
Use Vavr Option in Spring 6 RequestParam