MyBatis的学习笔记

一、mapper.xml 头部文件:

<?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>

二、查询

1.简单查询

<select id="findActiveBlogLike" resultType="Blog" parameterType="Blog">
  SELECT * FROM BLOG 
  <where> 
    <if test="state != null and state != ''">
         state = #{state}
    </if> 
    <if test="title != null and title != ''">
        title LIKE CONCAT ('%', #{title}, '%')
    </if>
  </where>
</select>

2.含 in 关键字的查询

<select id="selectDemo" resultType="Blog" parameterType="java.lang.List">
  SELECT * FROM BLOG 
  <where> 
    <if test="idList != null and idList != ''" >
    	id in
        <foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
        	#{id}
        </foreach>
    </if>  
  </where>
</select>

三、新增

1.单次

<insert id="addComment" parameterType="NewsComment">
    insert into news_comment
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="newsid != null">newsid,</if>
        <if test="author != null">author,</if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="newsid != null">#{newsid},</if>
        <if test="author != null">#{author},</if>
    </trim>
</insert>

2.批量

<insert id="insertList" parameterType="java.util.List">
    insert into tableName (col1, col2, col3, col4)
    VALUES
    <foreach collection="list" item="mIterm" separator="," close=";">
        (#{mIterm.col1}, #{mIterm.col2}, #{mIterm.col3}, #{mIterm.col4})
    </foreach>
</insert>

四、修改

<update id="updateByPrimaryKeySelective" parameterType="Air">
    update air_quality_index
    <set>
      <if test="districtId != null and districtId != ''">
        districtId = #{districtId},
      </if>
      <if test="monitorTime != null and monitorTime != ''">
        monitorTime = #{monitorTime},
      </if>
    </set>
    where id = #{id}
</update>

五、删除

<delete id="deleteByPrimaryKey" parameterType="int">
    delete from tableName where id = #{id}
</delete>

你可能感兴趣的:(ORM框架)