在 mapper.xml 中,可以使用以下方式编写 SQL 语句来实现基于实体类的查询:

  1. 使用'${}'占位符和属性名引用实体类的属性值:
<select id="selectByEntity" parameterType="com.example.Entity" resultType="com.example.Entity">
    SELECT * FROM my_table
    WHERE column1 = '${property1}'
    AND column2 = '${property2}'
</select>
  1. 使用'#{}'占位符和属性名引用实体类的属性值:
<select id="selectByEntity" parameterType="com.example.Entity" resultType="com.example.Entity">
    SELECT * FROM my_table
    WHERE column1 = #{property1}
    AND column2 = #{property2}
</select>
  1. 使用动态 SQL 语句:
<select id="selectByEntity" parameterType="com.example.Entity" resultType="com.example.Entity">
    SELECT * FROM my_table
    <where>
        <if test="property1 != null">
            AND column1 = #{property1}
        </if>
        <if test="property2 != null">
            AND column2 = #{property2}
        </if>
    </where>
</select>

此处的'property1'和'property2'均为实体类中的属性名称。在 MyBatis 中,使用'${}'引用的变量会以字符串形式直接替换到 SQL 语句中,而使用'#{}'引用的变量则会被 MyBatis 处理并转义为 SQL 参数,以避免 SQL 注入的风险。因此,为了避免 SQL 注入的风险,应该尽量使用'#{}'占位符。


原文地址: http://www.cveoy.top/t/topic/onij 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录