使用QueryDsl的java多态where子句
我试图使用QueryDsl编写一个带有多态where子句的查询
由于抽象地解释我想做什么有点困难,我cloned the spring-boot-sample-data-jpa project修改了它,以展示我正在尝试做的一个例子
我有these model classes,你会注意到SpaHotel
和SportHotel
扩展了Hotel
实体
我正在尝试编写一个查询,返回所有包含一个SpaHotel
或一个SportHotel
的城市,其主要运动类型为给定类型
我写了一篇JPQL version of that query,这有点难看(我不喜欢sport is null
部分表示这是一家温泉酒店),但似乎能回报我想要的东西
但是the QueryDsl version of that query似乎不起作用:
public List<City> findAllCitiesWithSpaOrSportHotelQueryDsl(SportType sportType) {
QCity city = QCity.city;
QHotel hotel = QHotel.hotel;
return queryFactory.from(city)
.join(city.hotels, hotel)
.where(
hotel.instanceOf(SpaHotel.class).or(
hotel.as(QSportHotel.class).mainSport.type.eq(sportType)
)
).list(city);
}
我的test在以下方面失败:
test_findAllCitiesWithSpaOrSportHotelQueryDsl(sample.data.jpa.service.CityRepositoryIntegrationTests) Time elapsed: 0.082 sec <<< FAILURE!
java.lang.AssertionError:
Expected: iterable over [<Montreal,Canada>, <Aspen,United States>, <'Neuchatel','Switzerland'>] in any order
but: No item matches: <Montreal,Canada> in [<Aspen,United States>, <'Neuchatel','Switzerland'>]
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
at sample.data.jpa.service.CityRepositoryIntegrationTests.test_findAllCitiesWithSpaOrSportHotelQueryDsl(CityRepositoryIntegrationTests.java:95)
我的查询似乎没有返回“Montreal”,它应该被返回,因为它包含一个SpaHotel
此外,我想知道QueryDsl将我的查询转换为交叉连接是否正常:
select city0_.id as id1_0_, city0_.country as country2_0_, city0_.name as name3_0_
from city city0_
inner join hotel hotels1_
on city0_.id=hotels1_.city_id
cross join sport sport2_
where hotels1_.main_sport_id=sport2_.id and (hotels1_.type=? or sport2_.type=?)
我的问题是:
- 为什么这个查询没有返回“Montreal”,它包含一个 斯帕酒店李>
- 有没有更好的方法来写这个问题李>
- 生成的SQL进行交叉连接是否正常?我们不能像我在JPQL中那样做左连接吗李>
共 (0) 个答案