Spring Data JPA find通过集合 [英] Spring Data JPA findBy a collection

查看:76
本文介绍了Spring Data JPA find通过集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆