MYBATIS常用的sql事例

今天整理了一下在项目中经常用到的mybatis的xml文件的sql语句:

读者:有sql基础。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper接口路径">
<!-- 假设一下的state为表中的字段 -->
<!-- 表的全部字段 -->
<sql id="selectId">
    表的全部字段-->select * from table_name中的*
</sql>
<!-- 批量插入sql语句 -->
<insert id="***">
    insert into table_name (columnName1,columnName2....)
    values
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.columnName1},#{item.columnName2}....)
    </foreach>
</insert>
<!-- if语句sql -->
<select id="***" parameterType="java.util.HashMap" resultType="java.lang.Integer">
    select count(1) from table_name where 1=1
    <if test="state != 1">
        and state=#{state}
    </if>
</select>
<!-- where语句sql -->
<select id="***" parameterType="参数类型" resultType="java.lang.Intege">
    select count(1) from table_name 
    <where>
        <if test="state != 1">
            and state=#{state}
        </if>
    </where>
</select>
<!-- choose语句sql 
    注:choose语句中的when是只要满足一个条件之后就放弃继续比较了,比较方式同Java中的Switch语句类似。
-->
<select id="***" parameterType="参数类型" resultType="java.lang.Integer">
    select <include refid="selectId" /> from table_name where 1=1
    <choose>
        <when test="state != 1">and state=#{state}</when>
        <otherwise>and state=0</otherwise>
    </choose>
</select>
<!-- set语句sql  更新
     注:set元素可以被用于动态包含更新的列,而不包含不需更新的
     这里,set 元素会动态前置 SET 关键字,而且也会消除任意无关的逗号,那也许在应用 条件之后来跟踪定义的值。
 -->
 <update id="***">
     update table_name
     <set>
         <if test="state != 1">state=#{state},</if>
         <if test="state == 1">state=0</if>
     </set>
     where id=#{id}
 </update>
 
 
 <!-- resultMap
     MyBatis的ResultMap使用方法,对象关联写法:http://blog.csdn.net/aya19880214/article/details/41960661
  -->
 <resultMap id="groupMap" type="java.lang.String">
    <result javaType="String" column="groupIds" property="groupIds"></result>
 </resultMap>
 <resultMap id="reportMap" type="java.util.Map">
    <result javaType="String" column="channelName" property="channelName"></result>
    <result javaType="String" column="channelPhone" property="channelPhone"></result>
    <result javaType="String" column="channelGroup" property="channelGroup"></result>
    ....
 </resultMap>
 <select id="queryChannelMarketingReport" resultMap="groupMap,reportMap" statementType="CALLABLE">
    CALL ChannelManagerMarketing(#{groupID},#{onTime},#{offTime})
 </select>
 <!--  mapper接口中的方法  注意返回类型List<List<Map<String,Object>>>
    List<List<Map<String,Object>>> queryChannelMarketingReport(@Param("groupID") String groupID, @Param("onTime") String onTime, @Param("offTime") String offTime);
 -->
 
 <!-- parameterMap用法
     MYBATIS中resultMap和parameterMap的使用:http://blog.csdn.net/aquarius_gamus/article/details/37704615
  -->    
</mapper>

供有需要的参考。

 

posted @ 2017-09-26 18:53  懒得烧蛇吃  阅读(205)  评论(0编辑  收藏  举报