Spring Data JPA findBy a collection [duplicate]

本小妞迷上赌 提交于 2020-05-13 06:15:06

问题


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:


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



来源:https://stackoverflow.com/questions/53619322/spring-data-jpa-findby-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!