增加数据:
¤ 例:
<insert id="add">
insert into tb_brand(brand_name, company_name, ordered, description, status)
values(#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
  ¤  增删改数据默认需要手动提交或者在获取sqlSession时传参关闭事务,否则数据库不会有变化
    ♦  手动提交方式:插入数据后调用sqlSession.commit();  
♦ 关闭事务方式:SqlSession sqlSession = sqlSessionFactory.openSession(true);
¤ 添加数据后的主键返回:可以在插入数据时获取到插入数据的主键值
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand(brand_name, company_name, ordered, description, status)
values(#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
修改数据:
¤ 修改全部字段
<update id="update">
update tb_brand
set
brand_name = #{brandName},
company_name = #{companyName},
ordered = #{ordered},
description = #{description},
status = #{status}
where id = #{id};
</update>
¤ 修改动态字段
<update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName != '' ">
brand_name = #{brandName},
</if>
<if test="companyName != null and companyName != '' ">
company_name = #{companyName},
</if>
<if test="ordered != null">
ordered = #{ordered},
</if>
<if test="description != null and description != '' ">
description = #{description},
</if>
<if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update>
删除数据:
¤ 删除一个
<delete id="deleteById">
delete form tb_brand where id = #{id};
</delete>
¤ 批量删除
<delete id="deleteByIds">
delete form tb_brand where id
in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
♦ MyBatis会将数组参数封装为一个Map集合
• 要遍历的字段是Map集合的key,默认:array
• 可以使用@Param注解修改Map集合默认key的名称:void deleteByIds(@Param("ids")int[] ids)
MyBatis参数封装:
¤ 单个参数:
♦ POJO类型:直接使用,属性名要和参数占位符名字一致
♦ Map集合:直接使用,集合中的键名要和参数占位符名字一致
♦ Collection:封装成Map,添加两条数据
• map.put("arg0", collection集合)
• map.put("collection", collection集合)
♦ List:封装成Map,添加三条数据
• map.put("arg0", list集合)
• map.put("collection", list集合)
• map.put("list", list集合)
♦ Array:封装成Map,添加两条数据
• map.put("arg0", 数组)
• map.put("array", 数组)
♦ 其它类型:直接使用
¤ 多个参数:自动封装成Map集合,可以使用@Param注解,替换默认的arg键名
♦ 每添加一个参数,会生成两对数据,在没有使用注解的情况下,可以通过默认的key来访问参数值
• map.put("arg0", 参数值1)
• map.put("param1", 参数值1)
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号