我有一个仓库。MEOfferRepository
@Repository
public interface MEOfferRepository extends JpaRepository<MEOfferDetailEntity, Long> {
@Query("select carrierId, carrierName from MEOfferDetailEntity entity where "
+ "(:countryCode is null or entity.carrierGeoAreaCode =:countryCode)")
CompletableFuture<Set<MEOfferDetail>> findCarrierByCountryCode(
final @Param("countryCode") String countryCode);
}
其中MEOfferDetailEntity是实体,MEOfferDetail是该实体的投影。
如果我提供一个有效的countryCode,这个查询可以正常运行,并且我得到了预期的结果,问题是当我把countryCode传递为null时。
我希望:countryCode is null能够运行,因为null是空的,而且查询会在没有where子句的情况下获取结果。
这个查询在MySql工作台中给出了预期的结果,但是在Spring boot JPA中,我得到的响应是一个空的集合,这不应该是这样。
我曾经遇到过同样的问题,后来我改变了语法,就成功了。
@Repository
public interface MEOfferRepository extends JpaRepository<MEOfferDetailEntity, Long> {
@Query("select carrierId, carrierName from MEOfferDetailEntity entity where " +
"entity.carrierGeoAreaCode = coalesce(:countryCode, entity.carrierGeoAreaCode)")
CompletableFuture<Set<MEOfferDetail>> findCarrierByCountryCode(
final @Param("countryCode") String countryCode);
}