一、定义SQL
1.1 select
定义语句为查询语句
1.2 update
定义语句为更新语句
1.3 delete
定义语句为删除语句
1.4 insert
定义语句为插入语句
二、配置结果映射集
resultMap标签
- 建立SQL查询结果字段与实体属性的映射关系信息
- 查询的结果集转换为java对象,方便进一步操作。
- 将结果集中的列与java对象中的属性对应起来并将值填充进去
<resultMap id="BaseResultMap" type="com.online.charge.platform.student.model.Student">
<id property="id" column="id" />
<result column="NAME" property="name" />
<result column="HOBBY" property="hobby" />
<result column="MAJOR" property="major" />
<result column="BIRTHDAY" property="birthday" />
<result column="AGE" property="age" />
</resultMap>
<!--查询时resultMap引用该resultMap -->
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
select id,name,hobby,major,birthday,age from student where id=#{id}
</select>
三、动态SQL拼接
if标签
常用于更新与插入语句中,以某一条件判断是否启用该字段作为SQL执行条件
<if test="name != null and name != ''">
and NAME = #{name}
</if>
foreach标签
主要用于批量删除,插入语句,与in关键字搭配使用
<!-- in查询所有,不分页 -->
<select id="selectIn" resultMap="BaseResultMap">
select name,hobby
from student where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
四、格式化输出标签
where标签
用于多个条件不确定具体哪一个存在时,使用where标签与if标签组合使用,可以取出SQL语句中多余的and关键字
<where>
<if test="name!=null and name!='' ">
NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
</if>
<if test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</if>
</where>
set标签
用于插入语句中不确定对象某个字段是否存在的情况下,set与if结合使用,用以去除多余的逗号
<set>
<if test="name!=null and name!='' ">
NAME = #{name},
</if>
<if test="hobby!=null and hobby!='' ">
MAJOR = #{major},
</if>
<if test="hobby!=null and hobby!='' ">
HOBBY = #{hobby}
</if>
</set>
五、定义常量与引用
sql标签
多用于查询或更新,将固定的重复SQL提取出来作为一个单独的SQL片段,以便复用
<!-- 查询字段 -->
<sql id="Base_Column_List">
ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY
</sql>
includ标签
用于将提取的SQL片段导入到SQL语句中,实现SQL片段的复用
<!-- 查询所有 -->
<select id="selectAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM
student
<include refid="Example_Where_Clause" />
</select>