我正在使用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表。
有没有人做过这样的事?您可能会提出任何优雅的解决方案吗?
任何帮助都将不胜感激!
发布于 2018-06-09 05:33:32
根据文档,您可以通过遍历嵌套属性来定义约束。请参阅2.4.3 Property Expressions
假设Country有一个属性regions,并且Country和Region都有name属性,您可以这样写:List<Country> findByNameAndRegions_Name(String countryName, String regionName)
发布于 2018-06-09 19:48:11
我认为这应该行得通:
interface CountryProjection {
String getCountryId();
String getCountryName()
String getRegionName()
}然后,您的查询方法可以如下所示:
List<CountryProjection> findByCountryNameAndRegionRegionNameAllIgnoreCase(String country,String region);您必须使用Spring Data JPA 1.10 a以后才能在查询方法中提供投影支持。
发布于 2018-06-09 13:51:06
按照建议的here,如果使用原生查询,看起来可以返回List<Object[]>。
虽然我更喜欢创建一个单独的DTO,因为这是一个不同的投影。
https://stackoverflow.com/questions/50768209
复制相似问题