MyBatis 注解和动态SQL语句

MyBatis 注解

MyBatis支持XML和注解两种方式

MyBatis注解与XML映射文件不同之处在于不需要创建XML映射文件


MyBatis 动态SQL语句

动态SQL是MyBatis的一个强大的特性之一,它是基于OGNL表达式的,可以帮助开发者方便的在SQL语句中实现某些业务逻辑


  • if

  • choose(when/otherwise)

  • trim

  • where

  • set

  • foreach


动态条件查询

动态条件查询是指当查询条件动态改变时,不同的查询条件对应不同的SQL语句

if 元素:if 元素用来实现动态条件查询,可以根据不同的查询条件自动拼接SQL语句,它的使用类似于 java 的 if 条件语句


语法格式

<if test = '查询条件'> SQL语句片段 </if>

XML配置文件例子

<?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">
<!--namespace表示命名空间,填写Mapper映射器接口全路径-->

<mapper namespace="dao.IUserAnnotation">
    <select id="selectByNameAndAgeAndSex" resultType="entity.UserEntity">
        select * from tb_user
        <where>
            <!--根据参数判断条件,满足条件则拼接SQL语句-->
            <if test="name !=null">
                and name = #{name}
            </if>
            <if test="age !=0">
                and age = #{age}
            </if>
            <if test="sex !=null">
                and sex = #{sex}
            </if>
        </where>
    </select>
</mapper>
原文地址:https://www.cnblogs.com/tantanli/p/13800079.html