在使用fluent-mybatis构建查询条件时,可以使用where方法来添加查询条件,并通过链式调用来进行条件组合。要改变条件的优先级,可以使用bracket方法来添加括号。

以下是一个示例代码:

import cn.org.atool.fluent.mybatis.If;
import cn.org.atool.fluent.mybatis.base.crud.IQuery;
import cn.org.atool.fluent.mybatis.base.model.Column;
import cn.org.atool.fluent.mybatis.base.model.FieldMapping;
import static cn.org.atool.fluent.mybatis.base.model.SqlOp.*;

public class UserQuery implements IQuery<UserQuery> {
    private static final UserMapping MAPPER = UserMapping.MAPPER;
  
    private final Column<UserQuery> column;
  
    public UserQuery() {
        this.column = new Column<>(this.getClass());
    }
  
    public UserQuery where(If<UserQuery, ?>... ifs) {
        return this.where(AND, ifs);
    }
  
    public UserQuery where(String exp, If<UserQuery, ?>... ifs) {
        this.column.where(exp, ifs);
        return this;
    }
  
    public UserQuery bracket(If<UserQuery, ?>... ifs) {
        this.column.bracket(ifs);
        return this;
    }
  
    public UserQuery bracket(String exp, If<UserQuery, ?>... ifs) {
        this.column.bracket(exp, ifs);
        return this;
    }
  
    public UserQuery selectId() {
        this.column.select(MAPPER.id);
        return this;
    }
  
    public UserQuery selectName() {
        this.column.select(MAPPER.name);
        return this;
    }
  
    public UserQuery whereIdEq(Long id) {
        this.column.eq(MAPPER.id, id);
        return this;
    }
  
    public UserQuery whereNameLike(String name) {
        this.column.like(MAPPER.name, name);
        return this;
    }
  
    public UserQuery orderBy(String... columns) {
        this.column.orderBy(columns);
        return this;
    }
  
    public UserQuery orderByDesc(String... columns) {
        this.column.orderByDesc(columns);
        return this;
    }
  
    public UserQuery limit(int limit) {
        this.column.limit(limit);
        return this;
    }
  
    public UserQuery limit(int limit, int offset) {
        this.column.limit(limit, offset);
        return this;
    }
}

在以上示例代码中,bracket方法用于添加括号,可以在括号内部组合条件。例如:

UserQuery query = new UserQuery();
query.where(query.bracket(q -> q.whereNameLike("John").or(q -> q.whereIdEq(1)))
    .and(q -> q.whereIdEq(2)));

上述代码将会生成如下SQL语句:

WHERE (name LIKE '%John%' OR id = 1) AND id = 2

通过使用bracket方法,可以改变条件的优先级

fluent-mybatis的Query构建查询条件where条件怎么添加括号改变优先级

原文地址: http://www.cveoy.top/t/topic/ishm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录