【问题标题】:Spring JPA Repositories: How to send default value to parameter if criteria is not matchingSpring JPA 存储库:如果条件不匹配,如何将默认值发送到参数
【发布时间】:2016-12-26 10:14:59
【问题描述】:
@Repository
public interface WANRepository  extends JpaRepository<WANConfiguration,Long>{
    @Query("select ads from WANConfiguration as ads where ?1 BETWEEN ads.minAge AND ads.maxAge AND ads.expiryTime >?2 and ads.region=?3 and ads.gender=?4")
    List<WANConfiguration> findByAllAdsForUser(Integer userAge,Date currentTime,String region, String gender);
}

这里是调用代码

List<WANConfiguration> list = fanRepository.findByAllAdsForUser(userAgeInYear, new Date(),userLocation.getRegionName(), user.getGender().name());

现在有一种情况我想传递默认区域,即 userLocation.getRegionName(),那么我该怎么做?在 db 和存储库或 Query 中需要做哪些更改?

【问题讨论】:

  • 你能清楚你在这里问什么吗?当userLocation.getRegionName() 为空/null 等时,您想传递默认区域吗?
  • 是的,没错...我想在默认区域为空或为空时传递默认区域

标签: spring jpa orm spring-data spring-data-jpa


【解决方案1】:

你可以在上面创建方法层:

List<WANConfiguration> findByAllAdsForUser(Integer userAge,Date currentTime,String region, String gender) {
     if(region == null || region.isEmpty()) {
         String defaultRegion = "what you want";
         return findByAllAdsForUser(userAge, currentTime, defaultRegion, gender);
     } 
     return findByAllAdsForUser(userAge, currentTime, region, gender);
}

【讨论】:

  • 做了同样的事情并得到了结果。实际上我是 JPA 和 Spring 的新手,我想一些不同的东西,这就是为什么我有点困惑......谢谢...... @ByeBye
  • 这样做是个好方法。如果我有帮助,请接受我的回答。
猜你喜欢
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多