【问题标题】:How to avoid specifying SQL query on Spring Data JPA when an attribute comes from another table当属性来自另一个表时,如何避免在 Spring Data JPA 上指定 SQL 查询
【发布时间】:2018-11-18 23:04:34
【问题描述】:

我正在使用 Spring Data JPA,并且我有以下实体: 国家:{country_id, country_name} 地区:{region_id, region_name, country_id}

国家与地区之间存在单对多关系。

我有一个适用于 Country 的 JpaRepository,我有如下方法:

@Query("SELECT new org.example.CountryDTO(a.countryId, a.countryName, b.regionName ) FROM Country AS a left join Region AS lpd on a. countryId = r. countryId  WHERE a. countryId = LOWER(:country) and r.regionName= LOWER(:region) ”)
List<CountryDTO> find(@Param("country") String country, @Param("region") String region);

问题是,有什么方法可以避免必须指定 SQL 查询?理想情况下,我想做这样的事情:

List<CountryDTO> findByCountryAndRegionName(@Param("country") String country, @Param("region") String region);

不过,这似乎有点复杂,因为 region_name 列来自 Region 表。

有人做过类似的事情吗?您可能会提出什么优雅的解决方案?

任何帮助将不胜感激!

【问题讨论】:

标签: java spring-boot jpa spring-data-jpa


【解决方案1】:

根据文档,您可以通过遍历嵌套属性来定义约束。见2.4.3 Property Expressions

假设 Country 有一个属性 regions 并且 Country 和 Region 都有 name 属性,你可以这样写:List&lt;Country&gt; findByNameAndRegions_Name(String countryName, String regionName)

【讨论】:

  • 嗨@sébastien-helbert 谢谢你的建议。在这里问你一个问题,是否有必要为 Country 和 Region 分别设置一个存储库?我问你这个问题是因为目前我将创建的所有查询都只与 Country 相关,所以我没有 Region 的存储库。另一个问题是,这在没有关系的情况下是否有效?
  • 如果所有查询都与 Country 相关,则您不需要 Region Repository。关于关系,据我所知,没有关系就行不通,因为嵌套路径依赖关系名称/依赖属性名称。
【解决方案2】:

如果您使用本机查询,您似乎可以返回 List&lt;Object[]&gt;,如建议的 here

虽然我更喜欢创建一个单独的 DTO,因为这是一个不同的投影。

【讨论】:

    【解决方案3】:

    我认为这应该可行:

    interface CountryProjection {
      String getCountryId();
      String getCountryName()
      String getRegionName()
    }
    

    然后你的查询方法可以如下所示:

    List<CountryProjection> findByCountryNameAndRegionRegionNameAllIgnoreCase(String country,String region);
    

    您必须稍后使用Spring Data JPA 1.10 才能在查询方法中支持投影。

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2019-03-10
      • 2015-06-28
      • 2021-03-10
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 2015-03-25
      相关资源
      最近更新 更多