splProvider 實現動態sql

SqlProvider.java

package com.mybatis.provider;

import java.util.List;

import com.mybatis.pojo.UserInfo;

public class SqlProvider {
    /*
     * 
     *  sql 提供者 
     *  提供一個sqlStatement的sql字符串
     *  多條件查詢
     *  滿足條件,就根據條件生成sql 語句
     *  方法參數要跟接口映射的方法的參數一致
     *  接口映射的方法 從該類獲取sqlStatement
     */
    public String queryUserinfo(UserInfo user){
        String sqlStatement="select * from userinfo where 1=1 ";
        String id=user.getId();
        String name=user.getName();
        String password=user.getPassword();

        if(id!=null&&!"".equals(id)){
            sqlStatement+=" and id =#{id}";
        }
        if(name!=null&&!"".equals(name)){
            sqlStatement+=" and name =#{name}";
        }
        if(password!=null&&!"".equals(password)){
            sqlStatement+=" and password =#{password}";
        }
        return sqlStatement;
    }
}
@SelectProvider(
            //sqlProvider 提供者提供sqlstatement的方法,方法參數必須一致
            method="queryUserinfo",
            //sqlProvider 提供者類
            type=SqlProvider.class)
    List<UserInfo> queryUserinfo(UserInfo user);
@Test
    public void testSqlProvider(){
        UserInfoInterfaceMapping i = sqlSession.getMapper(UserInfoInterfaceMapping.class);
        UserInfo userinfo=new UserInfo();
        userinfo.setId("7");
        userinfo.setPassword("oracle");;
        List<UserInfo> result = i.queryUserinfo(userinfo);
        System.out.println(result.get(0).getName());

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章