mapper.xml使用循环语句

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mapper.xml使用循环语句

代码搬晕工   2022-05-23 我要评论

mapper.xml使用循环语句

mapper.java,传的参数是map

List<实体类> getList(Map<String,Object> paraMap);

mapper.xml

<!--select:对应sql的select语句, id:方法名,parameterType:参数类型,resultMap:返回对象类型(BaseResultMap:标签-->
<!--<resultMap id="BaseResultMap" type="实体类包路径"> 实体类的映射 不改的话一般都是这个名字)-->
<select id="getList" parameterType="java.util.Map" resultMap="BaseResultMap">
  select * from table where 
  <!-- 判断-->
  <if test="a!= null">
      a = #{a,jdbcType=VARCHAR}
  </if>
  <if test="list!= null">
    and id in
    <!-- for循环, item:循环后的值, index:循环下标列式for循环的 i ,collection:参数名-->
    <!-- open="(" close=")" separator="," 就是把循环的值组成 (item1,item2,item3)的格式-->
    <foreach item="item" index="index" collection="list" open="(" close=")" separator=",">
     #{item}
    </foreach>
  </if>
</select>

参数,数组,list都行

Map<String,Object> map = new HashMap<String, Object>();
map.put("a","参数");
map.put("list",数组、List都行)
List<实体类> list = mapper.getList(map);

mybatis xml循环语句

MyBatis很好的支持批量插入,使用foreach即可满足

首先创建DAO方法

package com.youkeda.comment.dao;
import com.youkeda.comment.dataobject.UserDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
@Mapper
public interface UserDAO {
    int batchAdd(@Param("list") List<UserDO> userDOs);
}
<insert id="batchAdd" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO user (user_name, pwd, nick_name,avatar,gmt_created,gmt_modified)
    VALUES
    <foreach collection="list" item="it" index="index" separator =",">
        (#{it.userName}, #{it.pwd}, #{it.nickName}, #{it.avatar},now(),now())
    </foreach >
</insert>

foreach相当于执行力java的for循环,他的属性:

  • collection指定集合的上下文参数名称比如这里的@Param("list")
  • item指定遍历的每一个数据的变量,一般叫it,可以使用it.userName来获取具体的值
  • index集合的索引值,从0开始
  • separator遍历每条记录并添加分隔符

除了批量插入,使用SQL in查询多个用户时也会使用

package com.youkeda.comment.dao;
import com.youkeda.comment.dataobject.UserDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
@Mapper
public interface UserDAO {
    List<UserDO> findByIds(@Param("ids") List<Long> ids);
}
<select id="findByIds" resultMap="userResultMap">
    select * from user
    <where>
        id in
        <foreach item="item" index="index" collection="ids"
                    open="(" separator="," close=")">
            #{item}
        </foreach>
    </where>
</select>
  • open

表示的是节点开始时自定义的分隔符

  • close

表示是节点结束时自定义的分隔符

执行后会变成:

select * from user where id in (?,?,?)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们