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?
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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With