Mybatis在.xml文件中的SQL书写

自定义SQL语句中需要关注的名词含义及其用法

  • mapper中的namespace的含义:namespace命名空间是指的mapper接口的全路径名,目的是为了保证SQL语句的唯一性。
    <mapper namespace="com.mapper.XXXMapper">
  • resultMap以及其中type和id的含义:resultMap代表返回值数据库类型和Java类型的映射,type值为返回一个pojo对象,id为一个id结果,标记出作为id的结果可以帮助提高整体性能。
<resultMap type="Pojo" id="PojoResult">
    <result property="属性名"    column="元素名"    />
</resultMap>
  • sql标签代表sql语句片段(可以是一条select语句,也可以是其中的id,type,若为后者,需要将select语句补充完整)
<sql id="selectPojoVo">
    select id, type
    from tablename(表名)
</sql>
  • select语句
<select id="selectPojoById" parameterType="Long" resultMap="PojoResult">
   	<include refid="selectPojoVo"/>
        where id = #{id}
</select>
<select id="selectPojoList" parameterType="Pojo" resultMap="PojoResult">
    <include refid="selectPojoVo"/>
    <where>
        <if test="id != null "> and id = #{id}</if>
        <if test="type != null "> and type = #{type}</if>
    </where>
</select>
  • insert语句
<insert id="insertPojo" parameterType="Pojo" useGeneratedKeys="true" keyProperty="id">
    insert into tablename(表名)
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null">id,</if>
        <if test="type != null">type,</if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="id != null">#{id},</if>
        <if test="type != null">#{type},</if>
    </trim>
</insert>
  • update语句
<update id="updatePojo" parameterType="Pojo">
    update tablename(表名)
    <trim prefix="SET" suffixOverrides=",">
        <if test="type != null">type = #{type},</if>
    </trim>
    where id = #{id}
</update>
  • delete语句
<delete id="deletePojoById" parameterType="Long">
    delete from tablename(表名) where id = #{id}
</delete>
<delete id="deletePojoByIds" parameterType="String">
    delete from tablename(表名) where id in
    <foreach item="id" collection="array" open="(" separator="," close=")">
        #{id}
    </foreach>
</delete>
  • 对集合的处理(数组,list,map)
  1. foreach元素的属性主要有 item,index,collection,open,separator,close。
  2. collection标识参数中的属性,1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list,2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array。
  3. item表示集合中每一个元素进行迭代时的别名,
    index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
    open表示该语句以什么开始,
    separator表示在每次进行迭代之间以什么符号作为分隔符,
    close表示以什么结束。
  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值