MyBatis Mapper 传递多个参数

在pojo类对应的映射文件中,对应的参数类型可以省略。

传递方式
1. 接口正常书写,映射文件中SQL语句的占位符必须用 arg0 agr1…,或param1 param2…

接口:

public Customer getCustomerWithID(Integer id,String name);

对应的配置文件中的SQL语句:

 <select id="getCustomerWithID"  resultType="com.itlike.domain.Customer">
      <!--    select * from `customer` where cust_id=#{arg0} and cust_name=#{arg1}   -->
        select * from `customer` where cust_id=#{param1} and cust_name=#{param2}
    </select>

测试类中代码:

CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
Customer customerWithID = mapper.getCustomerWithID(2,"李白");

2.在接口中的形参前使用@param命名参数,映射文件中的SQL语句的占位符用@param命名的参数
注意,用@param命名后,SQL中的占位符不仅能用命名的名字,还能用param1 param2…但是不能用arg0 arg1…

接口:

public Customer getCustomerWithID(@Param("id") Integer id, @Param("name") String name);

对应的配置文件中的SQL语句:

 <select id="getCustomerWithID"  resultType="com.itlike.domain.Customer">
        select * from `customer` where cust_id=#{id} and cust_name=#{name}
    </select>

测试类中代码:

CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
Customer customerWithID = mapper.getCustomerWithID(2,"李白");

3.通过map来传递多个参数
接口:

 public Customer getCustomerWithID(Map<String,Object> map);

配置文件中的SQL语句:

   <select id="getCustomerWithID"  resultType="com.itlike.domain.Customer">
        select * from `customer` where cust_id=#{id} and cust_name=#{name}
    </select>

测试类中的代码:

 CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
 HashMap<String, Object> hashMap = new HashMap<>();
 hashMap.put("id",2);
 hashMap.put("name","李白");
 mapper.getCustomerWithID(hashMap);

注意:使用map传递多个参数,映射文件中的参数占位符必须和map中的String类型的字段名称一样
4.通过pojo类传递多个参数
与map传递多个参数类似,只不过映射文件中的参数占位符必须和pojo类中的字段完全一致才可以

接口:

public Customer getCustomerWithID(Customer customer);

配置文件中的SQL语句:

 <select id="getCustomerWithID"  resultType="com.itlike.domain.Customer">
        select * from `customer` where cust_id=#{cust_id} and cust_name=#{cust_name}
    </select>

pojo类:

public class Customer {
    private Integer cust_id;
    private String cust_name;
    private String cust_profession;
    private String cust_phone;
    private String email;
    }

测试类中的代码:

CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
Customer customer = new Customer();
customer.setCust_name("李白");
customer.setCust_id(2);
Customer customerWithID = mapper.getCustomerWithID(customer)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值