天天看点

MyBatis传多个参数的几种方式1. 传入对象类型2.用 Map 封装传递3.多个参数类型一样的情况,可以直接传入4.多个参数的类型不同时

MyBatis传多个参数的几种方式

  • 1. 传入对象类型
  • 2.用 Map 封装传递
  • 3.多个参数类型一样的情况,可以直接传入
  • 4.多个参数的类型不同时

1. 传入对象类型

在传参的时候传递一个对象类型,自然在获取的时候可以获取这个对象的所有属性, 所以对于传递多个参数 , 可以采用把多个属性封装到一个对象中的方法实现 . 列出一个例子 :

创建一个 PageBean 类

public class PageBean {
    private int page;
    private int pageSize;

    public int getPage() { return page;}
    public void setPage(int page) {this.page = page;}
    public int getPageSize() {return pageSize; }
    public void setPageSize(int pageSize) {this.pageSize = pageSize;}
}
           

在 …Mapper.java 中编写方法

在 …Mapper.xml 中编写查询语句

<select id="selectByPage_store" resultMap="BaseResultMap" parameterType="com.entity.PageBean">
    select
    <include refid="Base_Column_List" />
    from t_goods
    limit #{page},#{pageSize}
  </select>
           

因为传入的参数类型是 PageBean 类型的 , 所以可以 直接访问到 其属性 :page 和pageSize

2.用 Map 封装传递

在 Mapper.java 中传过来一个 map 类型的变量 ,其中设置有多对所要传的 键值对 ,

在 Mapper.xml 中把参数类型写为 map 类型的, 即: parameterType=“hashmap”,

在 放置变量的地方填写 map 中的 键 就可以了

例如 : name = #{ name } and pwd = #{ pwd } name 和 pwd 都是 map中 的键 key

例子如下:

在 service 中 设置 map 的键值对:

Private User SelectUser(){  
   Map map=new hashMap();  
   map.put(“name”,”对应具体的参数值”);  
   map.put(“pwd”,”对应具体的参数值”);  
   User user=xxx. selectUser(map);}  
           

Mapper.java 中编写方法,参数类型为 map

在 Mapper.xml 中编写语句

<select id=" selectUser" resultMap="BaseResultMap">  
   select  *  from user_user_t   where user_name = #{name} and user_pwd=#{pwd }  
</select>
           

3.多个参数类型一样的情况,可以直接传入

当想要传递的多个参数,类型相同时, 可以在 Mapper.xml 传参时 ,传入那个相同的参数类型 . 例如 ,想要传入两个参数类型为 Long 的值 , 那么就可以 进行如下操作:

在 Mapper.xml 中 编写方法,传入两个 类型为 long 的参数

在 Mapper.xml 中编写语句:

<select id="removeByPrimaryKey" parameterType="java.lang.Long">
    update
    t_goods
    set
    goodsStatus = 2
    where goodsId = #{goodsId} and  storeId= #{storeId}
  </select>
           

4.多个参数的类型不同时

所传递的多个值,采用 注解 的方式传递 , 语法格式为 :

在 Mapper.java 中

但是在 Mapper.xml 中接收的时候有两种方式接收 ,

(1) 通过 索引 的方式接收,(不是很推荐)

<select id="findList" resultType="com.qcby.entity.User" >
   select
   <include refid="Base_Column_List" />
   from user
   where  user_name = #{ arg0 }   and  user_age=#{ arg1 }
   //或者写为 where  user_name = #{ param1 }   and  user_age=#{ param2 } ...依次往下写
 </select>
           

(2) 通过传过来的名字获取 , 即 @param()中的字符串 .

<select id="findList" resultType="com.qcby.entity.User" >
    select
    <include refid="Base_Column_List" />
    from user
    where  id = #{ name  } or 1=1 and account=#{ age  }
  </select>