Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心。
1、parameterType(输入类型)
1.1、#{}与${}
#{}
实现的是向prepareStatement中的预处理语句中设置参数值,sql语句中#{}表示一个占位符即?。
使用占位符#{}可以有效防止sql注入
在使用时不需要关心参数值的类型,mybatis会自动进行java类型和jdbc类型的转换
可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。
<!-- 根据id查询用户信息 --> <select id="findUserById" parameterType="int" resultType="user"> select * from user where id = #{id} </select>
${}
和#{}不同,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换
可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。
使用${}不能防止sql注入,但是有时用${}会非常方便,如下的例子:
<!-- 根据名称模糊查询用户信息 --> <select id="selectUserByName" parameterType="string" resultType="user"> select * from user where username like '%${value}%' </select>
如果本例子使用#{}则传入的字符串中必须有%号,而%是人为拼接在参数中,显然有点麻烦,如果采用${}在sql中拼接为%的方式则在调用mapper接口传递参数就方便很多。
//如果使用#{}占位符号则必须人为在传参数中加% List<User> list = userMapper.selectUserByName("%管理员%"); //如果使用${}原始符号则不用人为在参数中加% List<User>list = userMapper.selectUserByName("管理员");
再比如order by排序,如果将列名通过参数传入sql,根据传的列名进行排序,应该写为:
ORDER BY ${columnName}
如果使用#{}将无法实现此功能。
1.2、传递简单类型
参考上边的例子。
1.3、传递pojo对象
Mybatis使用ognl表达式解析对象字段的值,如下例子:
<!—传递pojo对象综合查询用户信息 --> <select id="findUserByUser" parameterType="user" resultType="user"> select * from user where id=#{id} and username like '%${username}%' </select>
上边红色标注的是user对象中的字段名称。
注意参数名称,如果不一致,会产生异常。
1.4、传递pojo包装对象
开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
1.4.1、定义包装对象
定义包装对象将查询条件(pojo)以类组合的方式包装起来。
Vo:视图层对象
Po:持久层
Pojo:自定义的综合体
完成用户信息的综合查询,需要传入查询条件很复杂(可能包括用户信息、其它信息,比如商品、订单的)
package com.lhx.mybatis.po; public class QueryVo { private User user; // 自定义用户扩展类 private UserCustom userCustom; private String ordercode; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserCustom getUserCustom() { return userCustom; } public void setUserCustom(UserCustom userCustom) { this.userCustom = userCustom; } public String getOrdercode() { return ordercode; } public void setOrdercode(String ordercode) { this.ordercode = ordercode; } }
如果用户需要扩展
package com.lhx.mybatis.po; public class UserCustom extends User { private String phone; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
1.4.2 mapper.xml映射文件
<select id="findUserList" parameterType="com.lhx.mybatis.po.QueryVo" resultType="com.lhx.mybatis.po.User"> select * from user where #{user.username} and sex=#{user.sex} </select>
select * from user where sex=#{user.sex} and username like '%${user.username}%'
说明:mybatis底层通过ognl从pojo中获取属性值:#{user.username},user即是传入的包装对象的属性。queryVo是别名,即上边定义的包装对象类型。
1.4.3、编写Mapper
public List<User> findUserList(QueryVo queryVo) throws Exception;
1.5、传递hashmap
Sql映射文件定义如下:
<!-- 传递hashmap综合查询用户信息 -->
<select >username}%'
</select>
上边红色标注的是hashmap的key。
测试: