1. 程式人生 > 其它 >mybatis中的動態sql語句

mybatis中的動態sql語句

1、if標籤

熟悉的sql拼接:

    <select id="findUserByCondition" parameterType="User" resultType="User">
        select * from user where 1 = 1
        <if test="username != null and username != ''">
            and username like #{username}
        </if>
        <if test="sex != null and sex != ''">
            and sex = #{sex}
        </if>
    </select>

test程式碼:

    @Test
    public void testFindByCondition(){
        User user = new User();
        user.setUsername("%王%");
        user.setSex("男");
        List<User> users = dao.findUserByCondition(user);
        for(User u : users)
            System.out.println(u);
    }

2、where標籤

代替where 1 = 1的作用

    <select id="findUserByCondition" parameterType="User" resultType="User">
        select * from user
        <where>
        <if test="username != null and username != ''">
            and username like #{username}
        </if>
        <if test="sex != null and sex != ''">
            and sex = #{sex}
        </if>
        </where>
    </select>

3、foreach和sql標籤

foreach標籤
對著容器進行列舉操作

package com.czy.domain;

import java.util.List;

public class QueryVo {
    private User user;

    private List<Integer> ids;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        user.setUsername("%"+user.getUsername()+"%");
        this.user = user;
    }

    public List<Integer> getIds() {
        return ids;
    }

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}

  <select id="findUserInIds" parameterType="QueryVo" resultType="User">
        select * from user
        <where>
            <if test="ids != null and ids.size > 0">
                <foreach collection="ids" open="and id in (" close=")" separator="," item="id">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

sql標籤
用來映射覆用sql語句

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

    <select id="findUserInIds" parameterType="QueryVo" resultType="User">
        <include refid="defaultUser"></include>
        <where>
            <if test="ids != null and ids.size > 0">
                <foreach collection="ids" open="and id in (" close=")" separator="," item="id">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>