【MyBatis】動的SQL


if要素
説明:if条件の内容が満たされている場合は、SQL文の後に条件を追加します.
namespace="com.mapper.EmployeeMapper">
    <select id="selectEmployeeByIdLike" resultType="com.entity.Employee">
        select * from employee where state ='true'
        <if test="id != null">
            and id = #{id}
        if>
    select>

choose要素(when、otherwise)
説明:switch文と同様に、どの条件を満たすか、SQL後にこの条件を追加します.
namespace="com.mapper.EmployeeMapper">
    <select id="selectEmployeeChoose" parameterType="hashmap" resultType="com.entity.Employee">
        select * from employee where state ='true'
        
            <when test = "id != null">
                and id = #{id}
            when>
            <when test = "loginname != null">
                and loginname = #{loginname}
            when>
            
                and sex = '1'
            
        
    select>

where要素
説明:where句を挿入するには、if条件が1つ以上満たされている必要があります.
namespace="com.mapper.EmployeeMapper">
    <select id="selectEmployeeLike" resultType="com.entity.Employee">
        select * from employee
        <where>
            <if test="state != null ">
                state = #{state}
            if>
            <if test="id != null " >
                and id = #{id}
            if>
        where>
    select>

set要素
説明:if条件の内容が満たされている場合は、その内容を更新します.
<mapper namespace="com.mapper.EmployeeMapper">
    <update id="updateEmployee" parameterType="com.entity.Employee">
        update employee
        <set>
            <if test="loginname != null">loginname=#{loginname},if>
            <if test="password!= null">loginname=#{password},if>
            <if test="age!= null">loginname=#{age}if>
        set>
    update>
mapper>

bind元素
説明:コンテキストにバインドされた変数を作成します.
namespace="com.mapper.EmployeeMapper">
    <select id="selectEmployeeLikeName" resultType="com.entity.Employee">
        "pattern" value=" '%' + _parameter.getName() + '%' " />
        select * from employee where loginname like #{pattern}
    select>

小結
異なるSQL文では、OGLL式を使用して動的SQLを完了できます.