简体   繁体   中英

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

I have a update query in mapper interface using 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 {
private int addressId;
} 

Now the method where I am calling mapper Interface..I am sending a String postCode and object List addresses.

I am getting below error Caused by: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'item' not found. 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.

For the complex sql statments. I prefer to use SelectBuilder / UpdateBuilder .

See the last part of this page 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. Probably MyBatis doesn't see your #{item}, because it doesn't know about it (it treats all as SQL).

But, as Dean Xu sais, sql builder is better for more complicated queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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