常用元素有:id、parameterType、resultType、resultMap,设置缓存用到flushCache、useCache
传递多个参数
(1) 使用map接口传递参数–不推荐
接口:
List queryUserByMap(Map<String,Object> paramentMap);
service:
Map<String,Object> map=new HashMap<String,Object>();
map.put("userName", "张三");
map.put("mobile", "13800000000");
XML:
<select id="queryUserByMap" parameterType="map" resultType="com.bob.analyst.model.User" >
select
"Base_Column_List" />
from tbl_user
where user_name like concat('%',#{userName},'%')
and mobile like concat('%',#{mobile},'%')
select>
(2) 使用注解传递多个参数 —推荐
使用@Param(org.apache.ibatis.annotations.Param)
接口:
List queryUserByAnnotation(@Param("userName") String username,@Param("mobile") String mobile);
XML:
<select id="queryUserByAnnotation"resultType="com.bob.analyst.model.User" >
select
"Base_Column_List" />
from tbl_user
where user_name like concat('%',#{userName},'%')
and mobile like concat('%',#{mobile},'%')
select>
备注:这里不需要使用parameterType来表明参数类型,让MyBatis自动检索。
(3) 通过Java Bean传递多个参数
接口:
List<User> queryUserByBean(User user);
XML:
<select id="queryUserByBean" parameterType="com.bob.analyst.model.User" resultType="com.bob.analyst.model.User" >
select
"Base_Column_List" />
from tbl_user
where user_name like concat('%',#{userName},'%')
and mobile like concat('%',#{mobile},'%')
select>
(4) 混合使用
接口:
List queryUserByPage(@Param("user") User user,@Param("page") PageParam pageParam);
XML:
<select id="queryUserByPage" resultType="com.bob.analyst.model.User" >
select
"Base_Column_List" />
from tbl_user
where user_name like concat('%',#{user.userName},'%')
and mobile like concat('%',#{user.mobile},'%')
limit #{page.start}, #{page.limit}
select>
(5) 使用resultMap作为映射结果集
id="BaseResultMap" type="com.bob.analyst.model.User">
<id column="id" property="id" />
<result column="user_name" property="userName" />
<result column="mobile" property="mobile" />
<result column="password" property="password" />
resultMap 的 id 代表它的标识,type代表使用哪个类作为其映射类,可以使用别名或者全限定名.
id:代表resultMap的主键,而result代表其属性
property:代表POJO的属性名称,而column代表SQL的列名。
<resultMap id="BaseResultMap" type="com.bob.analyst.model.User">
<constructor>
<idArg/>
<arg/>
constructor>
<id/>
<result/>
<association property="">association>
<collection property="">collection>
<discriminator javaType="">
<case value="">case>
discriminator>
resultMap>
(6) 分页参数 RowBounds
接口:
List queryUserByRowBounds(@Param("userName") String username,@Param("mobile") String mobile,RowBounds rowBounds);
service:
RowBounds rowBounds=new RowBounds(0,20);
XML:
<select id="queryUserByRowBounds" resultType="com.bob.analyst.model.User" >
select
"Base_Column_List" />
from tbl_user
where user_name like concat('%',#{user.userName},'%')
and mobile like concat('%',#{user.mobile},'%')
select>
备注:它是MyBatis的一个附加参数,MyBatis会自动识别它。