簡體   English   中英

處理 QueryDSL 中的可選參數

[英]Handle optional parameters in QueryDSL

我在 SpringData 中使用 QueryDSL。 我有表說, Employee和我創建了實體類說, EmployeeEntity我寫了以下服務方法

public EmployeeEntity getEmployees(String firstName, String lastName)
{
    QEmployeeEntity employee = QEmployeeEntity.employeeEntity;
    BooleanExpression query = null;
    if(firstName != null)
    {
        query = employee.firstName.eq(firstName);
    }
    if(lastName != null)
    {
        query = query.and(employee.lastName.eq(lastName)); // NPException if firstName is null as query will be NULL
    }
    return empployeeDAO.findAll(query);
}

如上所述,我評論了NPException 如何使用QueryDSL為使用Spring數據在QueryDSL可選參數?

謝謝 :)

BooleanBuilder可以用作布爾表達式的動態構建器:

public EmployeeEntity getEmployees(String firstName, String lastName) {
    QEmployeeEntity employee = QEmployeeEntity.employeeEntity;
    BooleanBuilder where = new BooleanBuilder();
    if (firstName != null) {
        where.and(employee.firstName.eq(firstName));
    }
    if (lastName != null) {
        where.and(employee.lastName.eq(lastName));
    }
    return empployeeDAO.findAll(where);
}

BooleanBuilder 很好。 您還可以包裝它並添加“可選”方法以避免 if 條件:

例如,對於“and”,您可以編寫:(使用 Java 8 lambdas)

public class WhereClauseBuilder implements Predicate, Cloneable
{
    private BooleanBuilder delegate;

    public WhereClauseBuilder()
    {
        this.delegate = new BooleanBuilder();
    }

    public WhereClauseBuilder(Predicate pPredicate)
    {
        this.delegate = new BooleanBuilder(pPredicate);
    }

    public WhereClauseBuilder and(Predicate right)
    {
        return new WhereClauseBuilder(delegate.and(right));
    }

    public <V> WhereClauseBuilder optionalAnd(@Nullable V pValue, LazyBooleanExpression pBooleanExpression)
    {
        return applyIfNotNull(pValue, this::and, pBooleanExpression);
    }

    private <V> WhereClauseBuilder applyIfNotNull(@Nullable V pValue, Function<Predicate, WhereClauseBuilder> pFunction, LazyBooleanExpression pBooleanExpression)
    {
        if (pValue != null)
        {
            return new WhereClauseBuilder(pFunction.apply(pBooleanExpression.get()));
        }

        return this;
    }
   }

    @FunctionalInterface
    public interface LazyBooleanExpression
    {
        BooleanExpression get();
    }

然后使用會更干凈:

public EmployeeEntity getEmployees(String firstName, String lastName) {
    QEmployeeEntity employee = QEmployeeEntity.employeeEntity;

    return empployeeDAO.findAll
    (
       new WhereClauseBuilder()
           .optionalAnd(firstName, () -> employee.firstName.eq(firstName))
           .optionalAnd(lastName, () -> employee.lastName.eq(lastName))
    );
}

也可以使用 jdk 的 Optional 類

這實際上是 Java 101:檢查null並初始化查詢而不是連接謂詞。 因此,像這樣的輔助方法可以解決問題:

private BooleanExpression createOrAnd(BooleanExpression left, BooleanExpression right) {
  return left == null ? right : left.and(right);
}

然后你可以簡單地做:

BooleanExpression query = null;

if (firstName != null) {
  query = createOrAnd(query, employee.firstName.eq(firstName));
}

if (lastName != null) {
  query = createOrAnd(query, employee.lastName.eq(lastName));
}

…

請注意,我什至在第一createOrAnd(…)使用createOrAnd(…)只是為了保持一致性,並且如果您決定在firstName子句之前添加一個新子句,則不必修改該代碼。

如果您檢查null的 QueryDSL 實現:

public BooleanExpression and(@Nullable Predicate right) {
    right = (Predicate) ExpressionUtils.extract(right);
    if (right != null) {
        return BooleanOperation.create(Ops.AND, mixin, right);
    } else {
        return this;
    }
}

這應該是你想要的。

我遇到了同樣的問題,這里是Timo Westkämper使用Optional接受的答案的另一個版本。

default Optional<Correlation> findOne(
        @Nonnull final String value, @Nullable final String environment,
        @Nullable final String application, @Nullable final String service) {
    final QSome Some = QSome.some;
    final BooleanBuilder builder = new BooleanBuilder();
    ofNullable(service).map(some.service::eq).map(builder::and);
    ofNullable(application).map(some.application::eq).map(builder::and);
    ofNullable(environment).map(some.environment::eq).map(builder::and);
    builder.and(some.value.eq(value));
    return findOne(builder);
}

對於任何想要基於動態請求參數映射而不是特定的謂詞構建謂詞的人,可以使用以下簡單格式,


public List<User> searchUser(Map<String, Optional<String>> requestParams ){
        QUser qUser = Quser.qUser;
    
        BooleanBuilder builder = new BooleanBuilder();
        requestParams.forEach( (String key, String value) -> {
            if(!value.isEmpty()) {
                StringPath column = Expressions.stringPath(qUser, key);
               builder.and(column.eq(value));
            }
        });
  }

這是我的控制器

@RequestMapping(value = "", method = RequestMethod.GET) 
    public ResponseEntity<List<User>> searchUser(
            @RequestParam() Map<String, Optional<String>> requestParams) {

        List<User> userList = userService.searchUser(requestParams);
        
         if(userList!=null)
            return new ResponseEntity<>(userList, HttpStatus.OK);
        else
            return new ResponseEntity<>(userList, HttpStatus.INTERNAL_SERVER_ERROR);
    }

根據您的需要,我會這樣做

public List<EmployeeEntity> getEmployees(Optional<String> firstName, Optional<String> lastName)
{
    BooleanExpression queryPredicate =  QEmployeeEntity.employeeEntity.firstName.containsIgnoreCase(firstName.orElse("")).and(QEmployeeEntity.employeeEntity.lastName.containsIgnoreCase(lastName.orElse(""))); 
    return empployeeDAO.findAll(queryPredicate);
}

首先,您應該返回一個EmployeeEntity List 其次,使用 optional 比檢查它是否為null更好,您可以傳遞從可選RequestParam獲得的 Java 8 Optional值,如下所示:

@RequestMapping(value = "/query", method = RequestMethod.GET)
public ModelAndView queryEmployee(@RequestParam(value = "firstName", required = false) Optional<String> firstName, @RequestParam(value = "lastName", required = false) Optional<String> lastName) 
{
       List<EmployeeEntity> result =  getEmployees(firstName, lastName);    
            ....
}

一個非常重要的事情是在謂詞中使用containsIgnoreCase函數:它比典型的like更好,因為它不區分大小寫。

在我看來,你應該使用這樣的方法:

@Controller
class UserController {

  @Autowired UserRepository repository;

  @RequestMapping(value = "/", method = RequestMethod.GET)
  String index(Model model, @QuerydslPredicate(root = User.class) Predicate predicate,    
          Pageable pageable, @RequestParam MultiValueMap<String, String> parameters) {

    model.addAttribute("users", repository.findAll(predicate, pageable));

    return "index";
  }
}

看看這里

這是處理可選參數的一種非常簡單的方法,我在我的項目中使用它:

    public List<ResultEntity> findByOptionalsParams(String param1, Integer param2) {
    QResultEntity qResultEntity = QResultEntity.resultEntity;
    final JPQLQuery<ResultEntity> query = from(qResultEntity);
    if (!StringUtils.isEmpty(param1)) {
      query.where(qResultEntity.field1.like(Expressions.asString("%").concat(param1).concat("%")));
    }
    if (param2 != null) {
      query.where(qResultEntity.field2.eq(param2));
    }
    return query.fetch();
}

盡管結果查詢可能有點冗長,但還有另一種使用Optional而不使用BooleanBuilder方法:

public EmployeeEntity getEmployees(String firstName, String lastName) {
    QEmployeeEntity employee = QEmployeeEntity.employeeEntity;
    BooleanExpression where = ofNullable(firstName).map(employee.firstName::eq).orElse(Expressions.TRUE)
            .and(ofNullable(lastName).map(employee.lastName::eq).orElse(Expressions.TRUE));

    return empployeeDAO.findAll(where);
}

考慮到這個想法並添加一個輔助函數可以提高可讀性:

public EmployeeEntity getEmployees(String firstName, String lastName) {
    QEmployeeEntity employee = QEmployeeEntity.employeeEntity;
    BooleanExpression where = optionalExpression(firstName, employee.firstName::eq)
            .and(optionalExpression(lastName, employee.lastName::eq));

    return empployeeDAO.findAll(where);
}

public static <T> BooleanExpression optionalExpression(T arg, Function<T, BooleanExpression> expressionFunction) {
    if (arg == null) {
        return Expressions.TRUE;
    }
    return expressionFunction.apply(arg);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM