指针参数传递,MyBatis Mapper 传递多个参数

 2023-09-23 阅读 28 评论 0

摘要:在pojo类对应的映射文件中,对应的参数类型可以省略。 传递方式 1. 接口正常书写,映射文件中SQL语句的占位符必须用 arg0 agr1…,或param1 param2… 接口: public Customer getCustomerWithID(Integer id,String name); 对应的配置文件中的SQL语句: <s

在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);

java传递参数,对应的配置文件中的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,"李白");

mapper注入为null?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>

MyBatis?测试类中的代码:

 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)

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/95797.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息