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