SpaHotelSportHotelHotelSpaHotelSportHotelsport is null
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);
}
mythe QueryDsl version of that query失败的原因是:
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”,应该返回,因为它包含一个spahote。
另外,我想知道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”,其中包含
SpaHotel?
有没有更好的方法来编写这个查询?
生成的sql执行交叉连接是正常的吗?我们不能像在jpql中那样做左连接吗?
最佳答案:
jpql查询的正确转换
String jpql = "select c from City c"
+ " join c.hotels hotel"
+ " left join hotel.mainSport sport"
+ " where (sport is null or sport.type = :sportType)";
是
return queryFactory.from(city)
.join(city.hotels, hotel)
.leftJoin(hotel.as(QSportHotel.class).mainSport, sport)
.where(sport.isNull().or(sport.type.eq(sportType)))
.list(city);
在原始查询中,此属性的用法
hotel.as(QSportHotel.class).mainSport
导致交叉连接并将查询约束到SportHotels。
querydsl只对只在查询的orderby部分中使用的路径使用隐式左连接,所有这些都将导致隐式内部连接。