在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();
1条答案
按热度按时间ulmd4ohb1#
你可以使用一个参数Map...
}