mybatis输入输出映射及resultType和resultMap的使用

1.自增主键id的获取

  <!--数据插入,获取增长后的主键id-->
      <selectKey keyProperty="id" resultType="int" order="AFTER">
          select LAST_INSERT_ID()
      </selectKey>
        insert into user (username,sex,birthday,address)
        value (#{username},#{sex},#{birthday},#{address})
    </insert>

2.resultMap的使用

 <!--设置返回数据为resultMap-->
    <resultMap id="userResultMap" type="user">
        <!-- property中对应是包装类中的属性变量; column中对应的是数据空中的列名-->
        <id property="id" column="id_"></id>  <!--id property 填的是主键-->
        <result property="username" column="username_"></result>
        <result property="sex" column="sex_"></result>
        <result property="birthday" column="birthday_"></result>
        <result property="address" column="address_"></result>
    </resultMap>
    <select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
        select
          id id_,
          username username_,
          sex sex_,
          birthday birthday_,
          address address_
        from user where id = #{id}
    </select>

3.抽取出重复的查询条件代码,可以用sql标签

<!--抽取出重复的查询条件-->
    <sql id="select_user_where">
        <if test="user!=null">
            <if test="user.sex!=null and user.sex!=''">
                sex=#{user.sex}
            </if>
            <if test="user.username!=null and user.username!=''">
                and username like '%${user.username}%'
            </if>
        </if>
    </sql>

    <!--if和where的使用-->
    <select id="findUserList" parameterType="userQueryVo" resultType="user">
         select * from user
         <where>
           <!--引用上面抽取出来的-->
           <include refid="select_user_where"/>
         </where>
    </select>

4.用for each标签遍历数组集合的使用

   <!--for each 遍历的使用-->
    <select id="findUserByIds" parameterType="userQueryVo" resultType="user">
        <!-- select * from user where id in()
             collection: 集合,写集合属性
             item:遍历接收变量
             for(Integer id:ids)
             open: 遍历开始前的时候拼接上的元素
             close:遍历结束后的时候拼接上的元素
        -->
         select * from user
         <where>
           <if test="ids != null and ids.size>0">
             <foreach collection="ids" item="id" open="id in (" close=")" separator=",">
                 ${id}
             </foreach>
           </if>
         </where>
    </select>
      <select id="findUserByIds2" parameterType="list" resultType="user">
        select * from user
        <where>
            <if test="list != null and list.size>0">
                <foreach collection="list" item="id" open="id in (" close=")" separator=",">
                    ${id}
                </foreach>
            </if>
        </where>
    </select>
发布了35 篇原创文章 · 获赞 7 · 访问量 2121

猜你喜欢

转载自blog.csdn.net/weixin_40605573/article/details/103811289