通过使用MyBatis提供的标签方法可以实现动态SQL拼接

1if标签

<include refid="temp_sql"></include>这里代表select * from t_user

以上sql语句表示,如果money不为空或者money不是空字符串并且大于1000输出结果,否则输出查询所有

<select id="selectByMoney" resultType="demo.entity.User">
        <include refid="temp_sql"></include>
        <where>
        <if test="money!=null and money!=''">
            and money>1000
        </if>
        </where>
    </select>

2where标签

<select id="selectByMoney" resultType="demo.entity.User">
        <include refid="temp_sql"></include>
        <where>
        <if test="money!=null and money!=''">
            and money>1000
        </if>
        </where>
    </select>

where标签的作用是可以自动处理掉第一个and(可以参考if标ids为QueryVO对象的属性,属性的类型为List<Integer>。foreach标签签 

3foreach标签通过POJO传递List集合

 这里foreach相当于字符串拼接,但是不同的是open代表开始,item为里面放的内容,separaton代表以什么东西来分隔,close代表关闭

 <select id="selectByids" resultType="demo.entity.User">
        <include refid="temp_sql"></include>
        <where>
            <foreach collection="ids" open="and id in(" item="id" separator="," close=")">
                #{id}
            </foreach>
        </where>
    </select>

 4sql标签

将sql语句中放入<sql>标签中,可以除去繁琐的代码过程,下面可以调用 

5sql查询标签封装resultType(实体类路径)

 将相关配置放入application.yml文件中加入

type-aliases-package: demo.entity

后面黄色方框内容为路径,对应为实体类第一行package 

这样 resultType(实体类路径)就只写类名就行

如图所示 

更多推荐

MyBatis动态拼接SQL