Python 官方文档:入门教程 => 点击学习
目录mapper.xml使用循环语句mapper.java,传的参数是mapmapper.xml参数,数组,list都行mybatis xml循环语句首先创建DAO方法除了批量插入,
List<实体类> getList(Map<String,Object> paraMap);
<!--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>
Map<String,Object> map = new HashMap<String, Object>();
map.put("a","参数");
map.put("list",数组、List都行)
List<实体类> list = mapper.getList(map);
MyBatis很好的支持批量插入,使用foreach即可满足
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
遍历每条记录并添加分隔符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 (?,?,?)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: mybatis中的mapper.xml使用循环语句
本文链接: https://www.lsjlt.com/news/138385.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0