注意:以下传入数据与输出数据类型部分使用别名的方式,别名在SqlMapConfig.xml核心文件中配置
1.输入映射
1.1 传递简单数据类型
1.2 传递pojo中的类类型
1.3 传递QueryVo包装类
开发中通过可以使用pojo传递查询条件。查询条件可能是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如查询用户信息的时候,将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
1 package com.mybatis.pojo; 2 3 public class QueryVo { 4 5 private User user; 6 7 public User getUser() { 8 return user; 9 } 10 11 public void setUser(User user) { 12 this.user = user; 13 } 14 15 16 }
2.输出映射
2.1 输出简单数据类型
2.2 输出pojo类
2.3 输出列表
与输出类类型一致
2.4 手动指定查询结果映射(ResultMap)
一般情况采用ResultType会自动对应pojo类与表,前提表的字段与pojo类的属性一致。当出现不一致的时候,仍需要返回那么需要自定义。
1 <resultMap type="User" id="find"> 2 <id column="id" property="id"/> 3 <result column="username" property="username"/> 4 <result column="sex" property="sex"/> 5 <result column="address" property="address"/> 6 <result column="birthday" property="birthday"/> 7 </resultMap> 8 <select id="findUser" resultMap="find" > 9 select * from user 10 </select>
这里因为一致所以看不出效果。注意表中id需要用id标签对应
3.动态SQL
1 <!-- 根据条件查询User --> 2 <select id="findUserBySexAndUserName" parameterType="User" resultType="User"> 3 select * from User 4 where 1=1 5 <if test="sex != null and sex !=''"> 6 and sex = #{sex} 7 </if> 8 <if test="username != null and username != ''"> 9 and username like '%${username}%' 10 </if> 11 </select> 12 13 <!-- 根据条件查询User --> 14 <select id="findUserBySexAndUserNameByWhere" parameterType="User" resultType="User"> 15 select * from User 16 <where> 17 <if test="sex != null and sex !=''"> 18 and sex = #{sex} 19 </if> 20 <if test="username != null and username != ''"> 21 and username like '%${username}%' 22 </if> 23 </where> 24 </select>
两种标签if和where,if在test中写判断语句,where标签可以代替sql中的,能够将if语句中的and,是在前面的and给自动忽略。
当传入对个值时则需要foreach标签进行:假定传入的数据为List集合
1 <!-- 这里采用在包装类中定义list的方式作为传入值 2 原SQL语句为select * from user where id in(1,2,3) 3 collection:表示包装类中需要遍历的列表 4 item:表示每个数据的名字,需要与#{}中对应 5 separator:表示数据应“,”隔开 6 open:数据以这个开头 7 close:数据以这个结尾 8 --> 9 <select id="findUserByIds" parameterType="QueryVo" resultType="User"> 10 select * from user where id in 11 <foreach collection="ids" item="id" separator="," open="(" close=")"> 12 #{id} 13 </foreach> 14 </select>
其他的比如用数组传值这里就不介绍了。