Spring Data JPA find通过集合 [英] Spring Data JPA findBy a collection
问题描述
我正在使用JPA开发Java中的路由计划系统. 我需要创建一个findBy方法,以通过其所包含城市的列表来查找路线. 这是课程:
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);
}
是否有使用JPA的简便方法,还是我必须编写一个困难的@Query并以某种方式进行迭代以通过集合查找实体?
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?
推荐答案
您可以在RouteRepository
中更改方法的签名,以使用IN运算符.
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
这篇关于Spring Data JPA find通过集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!