Mybatis动态SQL示例

时间:2022-07-22
本文章向大家介绍Mybatis动态SQL示例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

<if> 不用我说的吧 <where> 可以帮你处理AND和OR的问题 (比如查询的时候) <set> 可以帮你处理逗号的问题(比如更新数据的时候) <trim> 可以自定义处理符号,相当于上面两个的自定义版本 <foreach> 可以循环list数据(比如批量插入数据或者批量查询条件 IN) choose、when、otherwise 用于当某个条件出现时,直接选择一个即可。

<?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="com.xn2001.mapper.UserDao">
    <insert id="save" useGeneratedKeys="true" keyProperty="id">
        insert into user(id,name,age) values
        (#{id},#{name},#{age})
    </insert>
    <insert id="insertForeach">
        insert into user
        (id,name,age) values
        <foreach collection="list" item="item" index="index" separator=",">
            (
            #{item.id},
            #{item.name},
            #{item.age}
            )
        </foreach>
    </insert>
    <update id="updateUser" parameterType="com.xn2001.entity.User">
        update user
        <set>
            <if test="name != null">
                name = #{name},
            </if>
            <if test="age != null">
                age = #{age}
            </if>
        </set>
        where id = #{id}
    </update>
    <select id="selectById" resultType="com.xn2001.entity.User">
        select * from user where id = #{id}
    </select>
    <select id="select" resultType="com.xn2001.entity.User">
        select * from user
        <where>
            <if test="id != null">
                id = #{id}
            </if>
            <if test="name != null">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
        </where>
    </select>
</mapper>