最近在复习javaee基础知识,从mybatis 开始,思考良久,撸之~
对于大多数人来说,mybatis在开发中遇到的问题都是参数的传递与结果集的封装与获取。针对这个情况,专门建立mybatis工程专项测试记录,欢迎大神指点。
mybatis的参数传递的几种情况
1.1 基本类型
User getUserById(@Param("userId") Integer userId);
<select id="getUserById" parameterType="int" resultType="user">
select * from user
<where>
<if test="userId != null">
id = #{userId}
</if>
</where>
</select>
使用方式:提供@Param注解指定参数别名方可在test中取值,因为mybatis采用ognl表达式的原因。
1.2 map传参
// b.使用map封装参数,map.key取值
User getUserByMap(Map<String, Object> param);
<select id="getUserByMap" parameterType="map" resultType="user">
select * from user
<where>
<if test="userId != null">
id = #{userId}
</if>
</where>
</select>
使用方式:
@Test
public void testGetUserById2() {
Map<String, Object> param = new HashMap();
param.put("userId",43);
User userById = mapper.getUserByMap(param);
logger.debug(userById);
}
将参数封装进map中,通过map.key的方式在xml中调用参数
1.3 对象传参
//封装查询条件
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
//c.使用 通用查询对象封装参数 ,属性取值
User getUserByVo(QueryVo queryVo);
<select id="getUserByVo" parameterType="queryVo" resultType="user">
select * from user
<where>
<if test="user.id != null">
id = #{user.id}
</if>
</where>
</select>
使用方式:
属性.子属性 user.username user.id
另外,还有集合传参,xml中使用foreach标签接受参数,主要是使用方式不一样,但是mybatis取参数的方式是一样的。
总结:关于mybatis的参数传递,只需要搞清楚ognl在mybatis的应用就可以基本解决参数传递过程中的大部分问题,对于喜欢研究底层代码的同学来说,这个就足够了。