在 Mybatis Dynamic SQL 中组合 AND 和 OR(例如使用圆括号)

Combining AND and OR (e.g. with round brackets) in Mybatis Dynamic SQL

我需要构建一个复杂的查询,部分来自“过滤器框架”。过滤器框架是一个反射组件,可以自动添加尽可能多的 and 个过滤器。

我已成功创建过滤器框架,该框架可根据用户通过 MVC 输入的内容生成 and 个过滤器。以下是一个典型的查询

SELECT * from Entity
WHERE
    attribute1 = ?
AND attribute2 > ?
AND attribute3 IN (????);

在 Mybatis Dynamic SQL 中,将调用链接到 AbstractWhereDSL.and 就完成了。

鉴于我有一个自动生成的 WhereApplier 的引用,它是一个 Consumer<AbstractWhereDSL<?>>,我需要链接另一个复杂的条件。结果查询必须是

SELECT * from Entity
WHERE
    attribute1 = ?
AND attribute2 > ?
AND attribute3 IN (????)
AND (
        (attribute4 = ? AND attribute5 IN (???))
    OR  (attribute4 = ? AND attribute5 IN (???))
    OR  (attribute4 = ? AND attribute5 IN (???))
)
;

AbstractWhereDSL 只接受 BindableColumnExistsPredicate.

如果我做类似的事情

ret = ret.applyWhere(where -> where
    .and(attribute4,isEqualTo(x)).and(attribute5,isIn(y))
    .or(attribute4,isEqualTo(z)).and(attribute5,isIn(a))
);

我将以平面查询结束

SELECT * from Entity
WHERE
    attribute1 = ?
AND attribute2 > ?
AND attribute3 IN (????)

AND attribute4 = ?
AND attribute5 IN (???)
OR  attribute4 = ?
AND attribute5 IN (???)
OR  attribute4 = ?
AND attribute5 IN (???)
;

这在我的场景中很糟糕。

问题:如何在Mybtis Dynamic中的where条件下创建子谓词SQL?

Context:虽然我已经与团队多次讨论过这个问题,但我需要根据基于属性的可见性来隔离查询。属性是两个,必须组合。我已经优化了查询,将权限集中具有相同 attribute4(工作流类型)的 attribute5(法人实体 ID)的所有值分组,否则最终查询将变成无穷无尽的列表(attribute4 = ? and attribute5 = ?)

在这种情况下,attribute4 in (?) and attribute5 in (?) 会非常简单,但有些结果是可以接受的(您可以在工作流 PERFORMANCE 中看到法律实体 ACME,但在 COMPLIANCE 中看不到,举个例子)

如果你使用的是mybatis-dynamic-sql库版本1.4.0,它支持where条件的分组。请参考以下git link参考

https://github.com/mybatis/mybatis-dynamic-sql/blob/master/src/test/java/examples/complexquery/GroupingTest.java