java MyBatis“或”标准

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26504185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:02:16  来源:igfitidea点击:

MyBatis "or" criteria

javamybatis

提问by Fergus MacDubh

I want to create a query with MyBatis, which will produce something like:

我想用 MyBatis 创建一个查询,它会产生如下结果:

SELECT first_field, second_filed, third_field
WHERE first_field > 1 AND (second_field > 0 OR third_field < 0)

How could I construct that with Criteria objects?

我怎么能用 Criteria 对象构造它?

采纳答案by Fabien Benoit-Koch

One way to do this would be to extend the generated Example classes:

一种方法是扩展生成的示例类

The generated "example" class includes a nested inner class where the actual functionality of the predicates exists. This inner class is always named GeneratedCriteria.

MBG also generates an inner class named Criteria which extends GeneratedCriteria and which you may use for adding your own functions to the example classes. The Criteria class will not be deletedby the Eclipse Java code merger, so you may add to it without fear of losing your changes upon regeneration.

生成的“示例”类包括一个嵌套的内部类,其中存在谓词的实际功能。这个内部类总是被命名为 GeneratedCriteria。

MBG 还生成一个名为 Criteria 的内部类,它扩展了 GeneratedCriteria 并且您可以使用它向示例类添加自己的函数。Criteria 类不会被Eclipse Java 代码合并删除,因此您可以添加到其中而不必担心在重新生成时丢失您的更改。

So basically,generate your example class, and add your custom criteria.

所以基本上,生成您的示例类,并添加您的自定义条件。

    public Criteria multiColumnOrClause(String value1, String value2) {
        addCriterion("value1 = " + value1 + " OR value2 = " + value2);
        return this;
    }

If you reuse it often, and don't want to do this for all your mappers, you can also extract the logic in a "plugin", although the documentation is a bit lacking on this, there's only one example :

如果您经常重用它,并且不想为所有映射器执行此操作,您也可以在“插件”中提取逻辑,尽管文档对此有点缺乏,但只有一个示例:

org.mybatis.generator.plugins.CaseInsensitiveLikePlugin

org.mybatis.generator.plugins.CaseInsensitiveLikePlugin

回答by Mike

Since a AND (b OR c)is the same as (a AND b) or (a AND c)

因为a AND (b OR c)是一样的(a AND b) or (a AND c)

TestTableExample example = new TestTableExample();
example.createCriteria()
  .andField1GreaterThan(1)
  .andField2GreaterThan(0);
example.or(example.createCriteria()
  .andField1GreaterThan(1)
  .andField3LessThan(0));

then sit back and let the SQL optimizer figure it out.

然后坐下来让 SQL 优化器计算出来。

回答by Fergus MacDubh

As far as I understand now, there is no possibility to do that with standard generated mapper.

据我现在了解,使用标准生成的映射器不可能做到这一点。