天天看點

mybatis 傳遞基本參數和模型參數到mapper.xml中

1.第一種 :基本參數的傳遞

mapper.java

public interface Some_ModelMapper extends Mapper<Some_Model> {
    public List<Some_Model> selectByMobileAndType(String phone,Integer ordertype);
}
           

在xml 中擷取從mapper接口傳過來的參數的值(假設table_name表(Some_Model模型)中有phone和ordertype兩個字段)

xml檔案

select FROM table_name WHERE  table_name.id=#{0})
    <if test="param1!=null">
     table_name.phone=#{0}
    </if>
    <if test="param2!=null and param2==2">
    table_name.ordertype=#{1}
    </if>
           

if判斷中param1代表第一個參數,在if以外的地方使用#{0}擷取第一個參數

2.第二種:mapper接口中直接傳模型(model)

mapper.java

public interface Some_Model extends Mapper<Some_Model> {
    public List<Some_Model> select_by_condition(Some_Model some_Model );
}
           

xml中擷取參數值時,在if中直接根據model的屬性擷取 比如model中有個屬性是name,則在if中直接寫name即可擷取。在if以為則在 #{ } 中擷取 ,比如#{name}

xml檔案

<select id="select_by_condition" parameterType="model_url.Some_Model " resultMap="BaseResultMap">  
 select * from table_name where table_name.area=#{area}  
 <if test="name !=null and name!=''">  
    and table_name.name like  CONCAT('%',#{name},'%')   
 </if>  
           

xml中不要使用${} , 存在sql注入漏洞。

繼續閱讀