效果:Spring Data JPA根据接口方法传入的值是否为空判断是否执行限定查询语句。
情景:最近在做项目的时候遇到一个问题,项目有一个 停车场表 ParkingLotsEntity,一个停车场产品表 FixedValidityTermEntity,现有一个方法 findAllByParkingLotId(String parkingLotId) 想根据传入的停车场id的值parkingLotId来查询对应的停车场产品,并且关联停车场表显示停车场的名称。parkingLotId为空则返回全部结果,不为空则返回部分结果。
//第一种方式,使用nativeQuery = true
@Query(value = "SELECT fixed,park.parkName AS parkName FROM FixedValidityTermEntity fixed " +
"LEFT JOIN ParkingLotsEntity park ON fixed.parkingLotId = park.id " +
"WHERE IF(:parkingLotId IS NOT NULL ,fixed.parkingLotId = :parkingLotId ,1 = 1 ) ",nativeQuery = true)
List<Object> findAllByParkingLotId(String parkingLotId);
//第二种方式
@Query(value = "SELECT fixed,park.parkName AS parkName FROM FixedValidityTermEntity fixed " + "LEFT JOIN ParkingLotsEntity park ON fixed.parkingLotId = park.id " +
"WHERE 1=1 AND (:parkingLotId IS NULL OR :parkingLotId = '' OR fixed.parkingLotId = :parkingLotId ) ")
List<Object> findAllByParkingLotId(String parkingLotId);