简体   繁体   English

如何在mybatis的mapper界面中编写foreach循环以进行更新查询

[英]how to write foreach loop for update query in mapper interface in mybatis

I have a update query in mapper interface using mybatis 我在使用mybatis的映射器界面中有一个更新查询

 final String UPDATE ="update table_addresses "
                            + "set postCode= #{postCode}"
                            + "where id in"
                            + "<foreach item='item' index='index' 
                               collection='addressId' "
                            + "open='(' separator=',' close=')'>  #{item} 
                 </foreach>";
@Update(UPDATE)
public int updateInformation(@Param("postCode") String postCode , 
@Param("addressId") List<AddressID> addressId);

My AddressId class contains int type addressId: 我的AddressId类包含int类型的addressId:

AddressId {
private int addressId;
} 

Now the method where I am calling mapper Interface..I am sending a String postCode and object List addresses. 现在,我正在调用mapper接口的方法。我正在发送一个字符串postCode和对象列表地址。

I am getting below error Caused by: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'item' not found. 我遇到以下错误原因:org.mybatis.spring.MyBatisSystemException:嵌套异常是org.apache.ibatis.binding.BindingException:找不到参数“ item”。 Available parameters are [param1, param2, postCode, addressId]..What Ia m doing wrong here.What is the correct syntax of foreach loop where I can pass addressId which conatins List. 可用的参数是[param1,param2,postCode,addressId]。这里我在做什么错。foreach循环的正确语法是什么,我可以在其中传递包含清单的addressId。

For the complex sql statments. 用于复杂的sql语句。 I prefer to use SelectBuilder / UpdateBuilder . 我更喜欢使用SelectBuilder / UpdateBuilder

See the last part of this page mybatis-java-api 参见本页最后部分mybatis-java-api

Try to wrap your whole SQL code in <script> tag like String SQL = "<script>(SQL goes here)</script>" if you use XML tags inside annotation defined query. 如果在注解定义的查询中使用XML标记,请尝试将整个SQL代码包装在<script>标记中,例如String SQL = "<script>(SQL goes here)</script>" Probably MyBatis doesn't see your #{item}, because it doesn't know about it (it treats all as SQL). MyBatis可能看不到您的#{item},因为它对此一无所知(它将全部视为SQL)。

But, as Dean Xu sais, sql builder is better for more complicated queries. 但是,正如Dean Xu所说的那样,对于更复杂的查询, sql builder更好。

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

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