Mybatis_dynamic sql

There are four parameters, none of which are required, so you need to find the data according to the filled content:

xml:

<!-- 
    The transfer type is the transfer object and the result type is map
    <![CDATA[XXXXXXXX]]> is to escape the less than sign
    -->
    <select id="selectPersonByCondition" parameterType="xxx.x.QueryCondition" resultMap="BaseResultMap">
        select * from person t
        <where>
            <if test="name != null">
                t.name like '%${name}%'
            </if>
            <if test="gender != null">
                and t.gender = #{gender}
            </if>
            <if test="personAddr != null">
                and t.person_addr like '%${personAddr}%'
            </if>
            <if test="birthday != null">
                <![CDATA[
                and t.birthday < #{birthday}
                ]]>
            </if>
        </where>
    </select>

java:

public void selectPersonByCondition() {
        //创建SqlSession
        SqlSession session = sessionFactory.openSession();
        try {
            QueryCondition qc = new QueryCondition();
            qc.setName( "Zhang San" );
            qc.setPerson_addr("shagnhai");
            qc.setGender(1);
            qc.setBirthday(new Date());
            List<Person> pList = session.selectList("xxx.x.mapper.PersonTestMapper.selectPersonByCondition",qc); 
            for(Person p : pList) {
                System.out.println(p);
            }
        }catch (Exception e) {
            e.printStackTrace ();
            session.rollback();
        }finally {
            session.close();
        }
        
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325461245&siteId=291194637