12

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?

Fuury
  • 121
  • 1
  • 1
  • 3

1 Answers1

10

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

Stefan Repcek
  • 2,553
  • 4
  • 21
  • 29