动态sql语句

根据实体类中属性是否被赋值来动态查询

使用if标签

如下:

<select id="findByCondition" parameterType="com.oylong.domain.User" resultMap="userMap">
select * from user where 1=1
<if test="username != null">
    and username = #{username}
</if>
</select>

使用if标签后,将判断test属性里面的条件是否成立,若成立,则将下面的sql语句与前面的sql语句拼接。其中test属性里面的判断属性,为传入的实体类的属性,需要与实体类属性相对应,其中包括大小写。

使用where标签

若条件多了,那么可以省略andwhere 1=1,但是需要使用where标签,如下:

<select id="findByCondition" parameterType="com.oylong.domain.User" resultType="com.oylong.domain.User">
    select * from user
    <where>
        <if test="username != null">
            and username = #{username}
        </if>
    </where>
</select>

foreach标签

select * from user
    <where>
        <foreach collection="ids" open="id in (" close=")" item="uid" separator=",">
            uid
        </foreach>
    </where>

其中

  • collection表示要遍历的集合
  • open表示固定的开始
  • close表示固定的结尾
  • item表示接受集合元素的变量
  • separator表示用什么分隔
  • 下面的标签值写内容

sql标签

很多重复的sql语句,可以用sql标签来代替,比如下面:

<sql id="all">
    select * from user
</sql>

<select id="findAll" resultType="com.oylong.domain.User">
        <include refid="all"></include>
</select>
最后修改:2020 年 03 月 23 日
如果觉得我的文章对你有用,请随意赞赏