mybatis秘籍之—— 标签
mybtis秘籍之 —— (CRUD) SQL语句
insert
- id :唯一的标识符
- parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User
<insert id="insert" parameterType="Object">
insert into student (student_id,stydent_name) values (#{studentId},#{stydentName})
</insert>
delete
- id :唯一的标识符
- parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User
<delete id="deleteById" parameterType="Object">
delete from student where id=#{id}
</delete>
update
- id :唯一的标识符
- parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User
<update id="alter" >
UPDATE student SET student_name= #{studentName} where student_id= #{studentId}
</update>
select
- id :唯一的标识符
- parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User 或 user
- resultType:语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与 resultMap不能并用)
<select id="findStudentById" resultMap="BaseResultMap" parameterType="Object">
select * from student where id=#{id}
</select>
mybatis秘籍之——动态SQL拼接
if 语句
if 标签通常用于 WHERE 后面,通过判断参数值来决定是否使用某个条件、插入某个字段的值。
<select id="findStudentById" resultMap="BaseResultMap" parameterType="Object">
select * from student where 1=1
<if test="studentId != null and studentId != ''">
and student_id =#{studentId }
</if>
<if test="studentName!= null and studentName!= ''">
and student_name =#{studentName}
</if>
</select>
foreach语句
foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。
属性:
- collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。
- item :表示在迭代过程中每一个元素的别名
- index :表示在迭代过程中每次迭代到的位置(下标)
- open :前缀
- close :后缀
- separator :分隔符,表示迭代时每个元素之间以什么分隔
<!-- 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>
choose语句
choose类似于 Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when的条件都不满则时,则执行 otherwise 中的 sql。
if 是与(and)的关系,而 choose 是或(or)的关系。
<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
SELECT * from STUDENT WHERE 1=1
<where>
<choose>
<when test="Name!=null and student!='' ">
AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
</when>
<when test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</when>
<otherwise>
AND AGE = 15
</otherwise>
</choose>
</where>
</select>