常用动态sql
动态 sql 是对于 mapper.xml 中 sql 语句的动态管理,以标签的形式管理 sql 语句
以下是常用的 动态sql 标签
<if text="bool"></if>
text 是必加属性,属性的值是一个条件判断语句,通常是对字段的条件判断
示例:
<select id="id" resultType = "car">
select * from t_car where
<if text="id" != null and id != ''>
id = "a096"
</if>
</select>
上面的语句当 所有条件都不成立 时,就会多余一个 where 关键字,导致 sql 语句错误,可以使用 where 标签解决
<where ></where>
当 sql 中多余 where 或者 多余 and ,or 时会自动删除
eg_change:
<select id="id" resultType = "car">
select * from t_car
<where>
<if text="id" != null and id != ''>
id = "a096"
</if>
</where>
</select>
<trim ></trim>
属性:
prefix :加前缀
suffix :加后缀
prefixOverrides :删除前缀
suffixOverrides :删除后缀
<trim prefix="where" suffixOverrides="and|or">
要执行的语句
</trim>
这条标签的作用是在要执行的语句前加上 where,若要执行的语句为空则不会添加
将多余的 and|or 关键字删除
<set ></set>
update 语句中的 set 关键字可以换成 set 标签
产生只更新不为空的字段的效果
<choose>...<when>...
<choose>
<when></when>
<when></when>
<otherwise></wotherwisehen>
</choose>
作用:
if(){
}else if(){
}else if(){
}else{
}
<foreach ></foreach>
<foreach collection="数组或集合" item="数组中的元素的名字" separator="循环分隔符"></foreach>
这里的 数组或集合 建议使用 Param 标签命名后调用
在循环中使用 数组中的元素的名字 就是使用每一次循环中的值
网页发送 get 请求:id=1&id=2&id=3
String[] ids = request.getParameterValues("id"); //拿到所有请求的id
ids = {1,2,3}
当传参为数组时,可以使用 foreach 标签遍历
常用注解
如果是简单的 sql 语句建议用注解
复杂的 sql 语句建议用 Mapper.xml 文件
注解写在 接口 的方法上
@insert("sql")
@Delete("sql")
@Update("sql")
@Select("sql")
如果出现 Pojo 类的属性名和数据库表中的 字段名不一致的情况
可以复合使用以下注解来指定匹配的名字
@Results({
@Result(property="属性名",column="字段名")
@Result(property="属性名",column="字段名") -> 设置数据库字段名和对应的属性名
@Result(property="属性名",column="字段名")
})
@Select("select * from t_birthday")
@Results({
@Result(property = "name",column = "name"),
@Result(property = "age",column = "age"),
@Result(property = "birthday",column = "birthday")
})
List<BirthBean> selectAll();
如果是 xml 文件中想要配置这些选项,则是使用 <resultMap id = "IDname" Type = "Pojo类"> 这个标签
<resultMap id = "I自定义name" Type = "Pojo类">
<id property="" column="">
<result property="" column="">
<result property="" column=""><result property="" column="">
</resultMap>