简体   繁体   English

MyBatis“或”标准

[英]MyBatis “or” criteria

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对象构造它?

One way to do this would be to extend the generated Example classes : 一种方法是扩展生成的Example类

The generated "example" class includes a nested inner class where the actual functionality of the predicates exists. 生成的“example”类包括嵌套的内部类,其中存在谓词的实际功能。 This inner class is always named GeneratedCriteria. 此内部类始终命名为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. MBG还生成一个名为Criteria的内部类,它扩展了GeneratedCriteria,您可以使用它来将自己的函数添加到示例类中。 The Criteria class will not be deleted by the Eclipse Java code merger, so you may add to it without fear of losing your changes upon regeneration. Eclipse Java代码合并不会删除Criteria类 ,因此您可以添加它,而不必担心在重新生成时丢失更改。

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

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优化器搞清楚。

据我所知,使用标准生成的映射器是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM