Mybatis传入参数及返回类型详解
一、Mybatis的三种传入参数的方式
1. 根据下标索引传值
通过传递参数的顺序进行索引,获得参数的值
Public User selectUser(String name,String area);
<select id="selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{0} and user_area=#{1}
</select>
其中#{0} 代表传入的第一个参数,之后依次进行索引。
2. 使用@param注解进行参数传递
先看例子:
Public User selectUser(@param(“userName”)Stringname,@param(“userArea”)String area);
<select id=" selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}
</select>
这种方法通过定义注解,设定参数的key值,在mapper.xml中通过key值进行获取,这种方法较为直观,但是参数数量较为固定。
3、通过map传递参数
Public User selectUser(Map paramMap);
<select id=" selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}
</select>
通过map的方式进行参数传递不需要固定参数的数量,在mapper中直接通过key值获得参数的值。
小结
这几种参数传递的方式每个人有每个人的习惯,可以在具体的项目中根据自己的使用习惯进行选择。
二、Mybatis的返回类型
1、返回参数类型
MyBatis的返回参数类型分两种
参数类型 | 对应的返回值类型 |
---|---|
resultMap | 可以返回一个list,也可以返回一个实体 |
resultType | int、string、long、class(实体) |
2、 指定返回resultType
<select id="queryCategoryBrandCount" resultType="java.lang.Integer" parameterType="java.util.HashMap" >
select count(1)
from common_category_brand
where 1=1
<if test="categoryId != null" >
and category_id = #{categoryId,jdbcType=BIGINT}
</if>
<if test="brandId != null" >
and brand_id = #{brandId,jdbcType=BIGINT}
</if>
</select>
3、 指定返回resultMap
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select
<include refid="Base_Column_List" />
from common_car_make
where id = #{id,jdbcType=BIGINT}
</select>
在返回ResultMap时,需要对之前对BaseResultMap中返回的值的类型进行指定,在执行select语句时返回相应的resultMap