java 在Hibernate中链接多个可选查询参数的最干净的方法是什么?

3pmvbmvn  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(154)

在hibernate中将多个可选参数链接到一个查询的最佳方法是什么?
做这样的事情感觉非常笨拙,但我看不到更好的方法:

StringBuilder builder = new StringBuilder("SELECT a from address a WHERE ");
    
if(!StringUtil.isNullOrEmpty(streetName)) {
  builder.append("a.streetName = :streetName AND ");
}
if(!StringUtil.isNullOrEmpty(houseNumber)) {
  builder.append("a.houseNumber = :houseNumber AND ");
}
if(!StringUtil.isNullOrEmpty(city)) {
  builder.append("a.city = :city AND ");
}
if(!StringUtil.isNullOrEmpty(countryCode)) {
  builder.append("a.countryCode = :countryCode AND ");
}
String sql = builder.substring(0, builder.length() - 4); //remove trailing 'AND'
  
TypedQuery<AddressEntity> query = entityManager.createQuery(sql, AddressEntity.class);
 
if(!StringUtil.isNullOrEmpty(streetName)) {
  query.setParameter("streetName", streetName);
}
if(!StringUtil.isNullOrEmpty(houseNumber)) {
  query.setParameter("houseNumber", houseNumber);
}
if(!StringUtil.isNullOrEmpty(city)) {
  query.setParameter("city", city);
}
if(!StringUtil.isNullOrEmpty(countryCode)) {
  query.setParameter("countryCode", countryCode);
}
  
return query.getResultList();
ulmd4ohb

ulmd4ohb1#

你可以使用一个参数Map...

private static Map<String, Object> parameters = new HashMap<>();

public static void main(String[] args) {
    parameters.put("streetName", "Linz");
    parameters.put("houseNumber", 1);
    
    String sql = parameters.entrySet().stream().map(e -> "a." + e.getKey() + " = :" + e.getKey()).collect(Collectors.joining(" AND "));
    
    TypedQuery<AddressEntity> query = entityManager.createQuery(sql, AddressEntity.class);
    
    parameters.entrySet().stream().forEach(e -> query.setParameter(e.getKey(), e.getValue()));
    
    return query.getResultList();
}

}

相关问题