在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。foreach元素的属性主要有 item,index,collection,open,separator,close。 item表示集合中每一个元素进行迭代时的别名, index指定一个名字,用于表示在迭代过程中,每次迭代到的位置, open表示该语句以什么开始, separator表示在每次进行迭代之间以什么符号作为分隔符, close表示以什么结束。
说明:以下示例关于MySQL数据库。 由于传入的参数是多个,因此把它们封装成一个Map了,当然单参数也可以用Map。.xml文件的部分代码如下:
<update id="updateMessage" parameterType="java.util.Map"> update cx_customer_message set MODIFYTIME = SYSDATE() where MEMBERID = #{memberId, jdbcType=VARCHAR} and MESSAGE_CLASSIFY = #{messageClassify, jdbcType=VARCHAR} and MESSAGE_CODE in <foreach collection="messageCode" item="item" index="index" open="(" separator="," close=")"> #{item,jdbcType=VARCHAR} </foreach> </update>MessageMapper.Java
public interface MessageMapper{ //更新 public int updateMessage(Map<String, Object> message); }MessageManager.java
public interface MessageManager { public int updateMessage(MessageReq messageReq); }MessageManagerImpl.java
@Component public class MessageManagerImpl implements MessageManager { @Autowired private MessageMapper messageMapper; @Override public int updateMessage(MessageReq messageReq) { int affectRows; Map<String, Object> message= new HashMap<String, Object>(); message.put("memberId", messageReq.getMemberId()); message.put("messageClassify",messageReq.getMessageClassify()); message.put("messageCode", messageReq.getMessageCode()); affectRows = messageMapper.updateDefualtMessage(message); return affectRows; } }collection属性是必须指定的,在不同情况下该属性的值是不一样的:
如上述例子,传入的参数是多个时,collection属性值为传入List或array在map里面的key; 传入的是单参数且参数类型是List时,collection属性值为list; 传入的是单参数且参数类型array时,collection的属性值为array。
