简体   繁体   English

如何使用 <foreach> MyBatis3在@SelectProvider类中的语句

[英]How to use <foreach> statement in @SelectProvider class with MyBatis3

I am trying to use @SelectProvider to create dynamic SQL by including the use of the tag foreach for a IN clause. 我试图用@SelectProvider通过包括使用标签来创建动态SQL foreachIN子句。 I know how to use it using the @Select annotation into my mapper. 我知道如何在映射器中使用@Select批注来使用它。

The problem is that when I translate the SQL into the SQLProvider it seem that the use it of the tag directly is not processed for the proxy that invoke SQLProvider method to get the SQL. 问题是,当我将SQL转换为SQLProvider时,似乎没有为调用SQLProvider方法获取SQL的代理直接处理标签的使用。

Here is the code example by using the @Select : 这是使用@Select的代码示例:

// imports...

public interface MyMapper {
    @Select({"<script>",
        "SELECT col_1, col_2", 
        "FROM table_1",
        "WHERE col_3 IN",
            "<foreach item='item' index='index' collection='items'",
                "open='(' separator=',' close=')'>",
                "#{item}",
            "</foreach>",
        "</script>"})
    HashMap<String, Object> select(@Param("items") String[] items);
}

The code above actually works, but when I try to use the @SelectProvider it doesn't works. 上面的代码实际上有效,但是当我尝试使用@SelectProvider它无效。

This is the code when I use @SelectProvider: 这是我使用@SelectProvider时的代码:

// imports...

public interface MyMapper {
    @SelectProvider(type = MySQLProvider.class, method = "select")
    HashMap<String, Object> select(@Param("items") String[] items);
}

public class MySQLProvider {
    public String select() {
        SQL sql = new SQL();
        sql.SELECT("col_1");
        sql.SELECT("col_2");
        sql.FROM("table_1");
        sql.WHERE("col_3 IN"
            + "<foreach item='item' index='index' collection='items'"
                + "open='(' separator=',' close=')'>"
                + "#{item}"
            + "</foreach>");
        return "<script>" + sql.toString() + "</script>";
    }
}

When I use the MyMapper it process the SQL well but ignore the script and foreach statements. 当我使用MyMapper它可以很好地处理SQL,但忽略scriptforeach语句。

Could anyone provide a concrete solution including the code? 谁能提供包含代码的具体解决方案?

As of MyBatis 3.5.1, <script> blocks defined in SqlProvider methods can now be processed. 从MyBatis 3.5.1开始,现在可以处理SqlProvider方法中定义的<script>块。 Your posted code should work if you upgrade to this version. 如果您升级到此版本,则发布的代码应该可以使用。

See the first bullet point under enhancements on the release notes here . 请在此处查看发行说明中增强功能下的第一个要点。

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

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