• Mybatis中传递多个参数的方法总结


    一、单个参数:

    public List<XXBean> getXXBeanList(String xxCode);  
    
    <select id="getXXXBeanList" parameterType="java.lang.String" resultType="XXBean">
    
      select t.* from tableName t where t.id= #{id}  
    
    </select>  
    
    其中方法名和ID一致,#{}中的参数名与方法中的参数名一直, 我这里采用的是XXXBean是采用的短名字,
    
    select 后的字段列表要和bean中的属性名一致, 如果不一致的可以用 as 来补充。



    二、多参数:
    public List<XXXBean> getXXXBeanList(String xxId, String xxCode);  
    
    <select id="getXXXBeanList" resultType="XXBean">
    
      select t.* from tableName where id = #{0} and name = #{1}  
    
    </select>  

    #{}里面的数字代表你传入参数的顺序。 由于是多参数那么就不能使用parameterType, 改用#{index}是第几个就用第几个的索引,索引从0开始


    @Param注解传参法
    public AddrInfo getAddrInfo(@Param("corpId")int corpId, @Param("addrId")int addrId);
     
    xml配置这样写:
     
    <select id="getAddrInfo"  resultMap="com.xxx.xxx.AddrInfo">
           SELECT * FROM addr__info 
        where addr_id=#{addrId} and corp_id=#{corpId} </select> 以前在<select>语句中要带parameterType的,现在可以不要这样写。

    三、Map封装多参数:
    public List<XXXBean> getXXXBeanList(HashMap map);  
    
    <select id="getXXXBeanList" parameterType="hashmap" resultType="XXBean">
    
      select 字段... from XXX where id=#{xxId} code = #{xxCode}  
    
    </select>  
    

    四、Java Bean传参法

    #{}里面的名称对应的是 User类里面的成员属性。

    这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。

     五、JSONObject参数

    <select id="listSelective" parameterType="com.alibaba.fastjson.JSONObject" resultType="com.alibaba.fastjson.JSONObject">
    SELECT c.*
    FROM car AS c
    WHERE 1=1
    <if test="id != null and id != ''">
    and c.id= #{id}
    </select>  

    Mapper:
    List<JSONObject> listSelective(JSONObject params);

     六、List封装in:

    public List<XXXBean> getXXXBeanList(List<String> list);  
    
    <select id="getXXXBeanList" resultType="XXBean">
      select 字段... from XXX where id in
      <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
        #{item}  
      </foreach>  
    </select>  
    
    foreach 最后的效果是select 字段... from XXX where id in ('1','2','3','4') 




    简单来说是以下规则:

    1、如果传递过来是单参数,且没有以@Param注解进行命名,则直接将单参数作为真实的参数调用SqlSession的对应方法。

    2、如果传递过来的不是单参数或者是包含以@Param注解进行命名的参数,则会将对应的参数转换为一个Map进行传递。具体规则如下:

          2.1、 会把对应的参数按照顺序以param1、param2、paramN这样的形式作为Key存入目标Map中,第一个参数是param1,第N个参数是paramN。

          2.2、 如果参数是以@Param注解命名的参数,则以@Param指定的名称作为Key存入目标Map中。

          2.3、 如果参数不是以@Param注解命名的,则按照顺序以0、1、N这样的形式作为Key存入目标Map中,第一个参数是0,第N个参数是N。

    
    
  • 相关阅读:
    AC自动机模板
    KMP 模板
    HDU 2746 Cyclic Nacklace
    LCS模板
    POJ 1159 Palindrome
    LIS n^2&nlogn模板
    Codeforces Round #Pi (Div. 2) C. Geometric Progression
    Codeforces Beta Round #25 (Div. 2 Only)E. Test
    Codeforces Beta Round #25 (Div. 2 Only)D. Roads not only in Berland
    bzoj5055 膜法师
  • 原文地址:https://www.cnblogs.com/panchanggui/p/11395808.html
Copyright © 2020-2023  润新知