Mybatis参数处理

单一参数

无特殊处理,参数名相当于占位符,#{任意}都能取出值

示例

XML映射:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper       
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lhx.dao.EmpDAO">
    <select id="selectById" resultType="employee">        
        select * from employee where id =#{abc}    
    </select>
</mapper>

接口方法:

Employee selectById(int id);

多参数处理

mybatis会把多个参数封装为一个map,#{name}的方法是通过对map对象key的取值。在默认情况下,mybatis会把参数列表封装为{param1,param2...paramN}的形式
这种情况下,mapper映射文件一般是这样的

<select id="selectByIdAndName" resultType="employee">  
    select * from employee where id=#{param1} and last_name=#{param2}
</select>

显然这种方式在参数多的情况下不是很方便

指定参数名

在接口的参数前使用注解@Param(“paramName”),在这种参数声明下,我们可以在mapper配置文件中使用自己定义的参数名称

mybatis封装的参数map会变为:

key:指定的参数名
value:传入的值
#{key}:取出对应的参数值

代码示例

接口:

public interface EmpDAO {    
        Employee selectByIdAndName(@Param("id") Integer id,@Param("name")String name);       
}

mapper映射文件:

<select id="selectByIdAndName" resultType="employee">    
    select * from employee where id=#{id} and last_name=#{name}
</select>

对象参数处理

如果多个参数正好是数据库实体类的对象,可以在参数中直接传入对象,这样,mybatis在使用 #{对象属性名}时也可以取出相应 的参数

代码示例

接口:

public interface EmpDAO {    
    Boolean update(Employee e);

实体类:

@Data
public class Employee {  
    private Integer id;
    private  String lastName;  
    private String gender;
    private String email;
}

mapper映射文件:

<update id="update" parameterType="employee">
    update employee set last_name=#{lastName} ,email=#{email},gender=#{gender} where id=#{id}
</update>

参数为集合类型

Map对象

既然mybatis为我们把参数列表封装成了Map对象,那么为了方便,我们也可以手动传入map对象,此时#{key}可以取出map中对应名称的值

代码示例

接口::

public interface EmpDAO {
      Employee selectByMap(Map<String,Object> map);
}

mapper映射文件:

<select id="selectByMap" resultType="employee">    
    select *from employee where id=#{id} and last_name=#{name}
</select>

其他集合类型

mybatis会把Collection(list,set)类型包括数组类型也封装在map中,但取值方式与map稍有不同

类型 :Collection
key:collecion[index]

类型:LIst
key:list[index]

类型:数组
key:array[index]

开发小技巧

当我们对一类参数使用频繁,但其不是数据库实体类时,可以将其封装为一个TO(transfer Object即数据传输对象)
例如:查询时我们通常会采取分页查询的方法,这时,可以编写一个分页的数据传输对象,里面包括每页的信息、分页大小等
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值