Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA findBy a collection [duplicate]

Im working on a route planing system in Java, using JPA. I need to create a findBy method to find an route by a list of the cities its containing. Here are the classes:

@Entity
public class Route {

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<City> cities = new ArrayList<>();
    .
    .
}

@Entity
public class City {
    .
    .
}

Now I tried, but wasn't surprised it didn't work, the following:

@Repository
public interface RouteRepository extends JpaRepository<Route, Long> {
    Optional<Route> findByCities(List<City> city);
}

Is there an easy way to do it with JPA, or do I have to write a difficult own @Query and somehow iterate, to find an entity by a collection?

like image 996
Fuury Avatar asked Dec 04 '18 18:12

Fuury


People also ask

How to derive query methods in spring data JPA?

1. Introduction For simple queries, it's easy to derive what the query should be just by looking at the corresponding method name in our code. In this tutorial, we'll explore how Spring Data JPA leverages this idea in the form of a method naming convention. 2. Structure of Derived Query Methods in Spring

What is @query annotation in spring data JPA?

Overview Spring Data provides many ways to define a query that we can execute. One of these is the @Query annotation. In this tutorial, we'll demonstrate how to use the @Query annotation in Spring Data JPA to execute both JPQL and native SQL queries. We'll also show how to build a dynamic query when the @Query annotation is not enough.

How to create finder methods in data JPA?

Behind the scenes, Data JPA will create SQL queries based on the finder method and execute the query for us. To create finder methods in Data JPA, we need to follow a certain naming convention. To create finder methods for the entity class field name, we need to create a method starting with findBy followed by field name.

What is the difference between find and byname in JPA?

The first part – like find – is the introducer and the rest – like ByName – is the criteria. Spring Data JPA supports find, read, query, count and get.


1 Answers

You can change the signature of your method in RouteRepository, to use IN operator.

@Repository
public interface RouteRepository extends JpaRepository<Route, Long> {
    Optional<Route> findByCitiesIn(List<City> cities);
}

Then it should work. However be aware it is not exact match. Check more on

https://docs.spring.io/spring-data/jpa/docs/2.1.x/reference/html/#jpa.query-methods

like image 71
Stefan Repcek Avatar answered Oct 07 '22 05:10

Stefan Repcek