1. 程式人生 > >mybatis遍歷集合List和陣列Array

mybatis遍歷集合List和陣列Array

一、遍歷集合

1.不用註解

public void insertList(List<User> users);
<insert id="insertList" parameterType="java.util.List" >
insert into user (id,name,password,sex,age)
values 
<foreach collection="list" open="(" close=")" separator="," item="item">
    #{item.id,jdbcType=INTEGER}, #{item.name,jdbcType=VARCHAR}, 
    #{item.password,jdbcType=VARCHAR}, #{item.sex,jdbcType=TINYINT}, 
    #{item.age,jdbcType=INTEGER}
</foreach>
</insert>

2.使用@Param註解

public void insertList(@Param List<User> users);
<insert id="insertList">
insert into user (id,name,password,sex,age)
values 
<foreach collection="users" open="(" close=")" separator="," item="item">
    #{item.id,jdbcType=INTEGER}, #{item.name,jdbcType=VARCHAR}, 
    #{item.password,jdbcType=VARCHAR}, #{item.sex,jdbcType=TINYINT}, 
    #{item.age,jdbcType=INTEGER}
</foreach>
</insert>

二、遍歷陣列Array

1.不用註解

public List<User> selectAllUsers(Integer[] ids);
<select id="selectAllUsers" parameterType="java.util.Array" >
select * from user where id in
<foreach collection="array" open="(" close=")" separator="," item="item">
       #{item,jdbcType=INTEGER}
</foreach>
</select

2.使用@Param註解

public List<User> selectAllUsers(@Param("ids") Integer[] ids);
<select id="selectAllUsers" parameterType="java.util.Array" >
select * from user where id in
<foreach collection="ids" open="(" close=")" separator="," item="item">
       #{item,jdbcType=INTEGER}
</foreach>
</select

三、遍歷兩個集合

List<SubOrgDetail> selectSubOrgDetail(@Param("params") Map<String, Object>;
<select id="selectSubOrgDetail" resultMap="BaseResultMapDetail">
SELECT org.org_id,org.org_name,t.goods_id,t.num,`user`.user_pic 
FROM 
organization org 
INNER JOIN 
    (SELECT belong_org,num,goods_id 
    FROM
    org_goods
    WHERE
    now_org = 1 AND
    belong_org in
    <foreach close=")" collection="params.orgIds" index="index" item="id" open="(" separator=",">
        #{id}
    </foreach>
    AND goods_id in         
    <foreach close=")" collection="params.goodIds" index="index" item="id" open="(" separator=",">
        #{id}
    </foreach>) t
ON
org.org_id=t.belong_org
INNER JOIN
`user`
ON
`user`.org_id=t.belong_org
</select>