本章节将介绍 MyBatis 怎样给 <select> 标签定义的 SQL 语句传递参数。
MyBaits 的 @Param 注解主要是用来修饰 DAO 类中方法的参数,便于在对应的 *-Mapper.xml 文件中引用,如:在 UserMapper 接口中有下面方法:
UserBean getUserByName(@Param("age") int age, @Param("username") String username);
上面的 getUserByName 方法定义了 age 和 username 参数。注意,使用 @Param 注解可以为方法指定多个参数,在查询语句中使用时可以使用 #{} 或 ${} 方式。
在 Mapper.xml 文件中使用 #{} 方式引用参数:
<!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo3.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 根据ID查询用户信息 --> <select id="getUserByName" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=#{age,jdbcType=INTEGER} and `name`=#{username,jdbcType=VARCHAR} </select>
在 Mapper.xml 文件中使用 ${} 方式引用参数:
<select id="getUserByName2" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=${age} and `name`='${username}' </select>
注意,上面的 SQL 语句中 ${username} 是放到一个单引号中的,如果你没有将 ${username} 放到单引号中,将抛出如下错误信息:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'ZhangSan' in 'where clause' ### The error may exist in com/hxstrive/mybatis/select/demo3/UserMapper.xml ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: select `user_id`, `name`, `sex`, `age` from `user` where age=28 and `name`=ZhangSan ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'ZhangSan' in 'where clause' at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:107) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:62)
上面错误原因是查询条件“ZhangSan”并没有放到单引号中。正确的SQL语句应该如下:
select `user_id`, `name`, `sex`, `age` from `user` where age=28 and `name`='ZhangSan'
在 MyBatis 中,如果不使用 @Param 注解传递参数,方法的参数只能有一个参数。如:在 UserMapper 接口中有下面方法:
UserBean getUserByName3(ArgBean argBean);
上面方法将 ArgBean 对象作为 DAO 参数。
在 Mapper XML 文件中可以使用 #{} 进行引用,如下:
<!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo3.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <select id="getUserByName3" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=#{age} and `name`=#{username} </select>
你也可以使用 ${} 引用参数,如下:
<select id="getUserByName4" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=${age} and `name`='${username}' </select>
如果我们为方法定义两个参数,会有怎样的结果呢?将会抛出 BindingException 错误,导致不能正确绑定参数。定义如下方法:
UserBean getUserByName5(ArgBean argBean, int userId);
该方法对应的 XML 内容如下:
<!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo3.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <select id="getUserByName5" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=${age} and `name`='${username}' </select>
运行程序后,程序抛出了如下错误信息:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter 'age' not found. Available parameters are [0, 1, param1, param2]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'age' not found. Available parameters are [0, 1, param1, param2]
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:107)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:62)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:43)
at com.sun.proxy.$Proxy2.getUserByName5(Unknown Source)
at com.hxstrive.mybatis.select.demo3.SelectDemo3.main(SelectDemo3.java:37)
因此,不使用 @Param 定义参数,方法只能定义一个参数。
(1)MyBatis 配置文件 mybatis-cfg.xml 内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/hxstrive/mybatis/select/demo3/UserMapper.xml" /> </mappers> </configuration>
(2)Mapper 接口 UserMapper.java 文件内容如下:
package com.hxstrive.mybatis.select.demo3; import org.apache.ibatis.annotations.Param; public interface UserMapper { /** 用 @Param 定义参数,允许使用 #{} 形式访问 */ UserBean getUserByName(@Param("age") int age, @Param("username") String username); /** 用 @Param 定义参数,允许使用 ${} 形式访问 */ UserBean getUserByName2(@Param("age") int age, @Param("username") String username); /** 非 @Param 定义的参数,允许使用 #{} 形式访问 */ UserBean getUserByName3(ArgBean argBean); /** 非 @Param 定义的参数,允许使用 ${} 形式访问 */ UserBean getUserByName4(ArgBean argBean); /** 非 @Param 定义的参数,只能定义一个;定义多个则会运行错误 */ UserBean getUserByName5(ArgBean argBean, int userId); /** 非 @Param 定义的参数,可以使用非 JavaBean */ UserBean getUserByName6(int userId); }
(3)Mapper XML 文件 UserMapper.xml 文件内容如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.select.demo3.UserMapper"> <!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo3.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 根据ID查询用户信息 --> <select id="getUserByName" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=#{age,jdbcType=INTEGER} and `name`=#{username,jdbcType=VARCHAR} </select> <select id="getUserByName2" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=${age} and `name`='${username}' </select> <!-- 如果 ${username} 没有放到单引号中,将抛出如下错误: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'ZhangSan' in 'where clause' ### The error may exist in com/hxstrive/mybatis/select/demo3/UserMapper.xml ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: select `user_id`, `name`, `sex`, `age` from `user` where age=28 and `name`=ZhangSan ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'ZhangSan' in 'where clause' --> <select id="getUserByName3" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=#{age} and `name`=#{username} </select> <select id="getUserByName4" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=${age} and `name`='${username}' </select> <select id="getUserByName5" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where age=#{age} and `name`=#{username} </select> <select id="getUserByName6" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where user_id=#{userId} </select> </mapper>
(4)参数 Bean ArgBean.java 文件内容如下:
package com.hxstrive.mybatis.select.demo3; public class ArgBean { private int age; private String username; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
(5)客户端,代码如下:
package com.hxstrive.mybatis.select.demo3; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class SelectDemo3 { public static void main(String[] args) throws Exception { String cfgName = "com/hxstrive/mybatis/select/demo3/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); UserBean userBean = userMapper.getUserByName(28, "ZhangSan"); System.out.println(userBean); userBean = userMapper.getUserByName2(28, "ZhangSan"); System.out.println(userBean); ArgBean argBean = new ArgBean(); argBean.setAge(28); argBean.setUsername("ZhangSan"); userBean = userMapper.getUserByName3(argBean); System.out.println(userBean); userBean = userMapper.getUserByName4(argBean); System.out.println(userBean); // 不使用 @Param 注解定义参数,一个方法只能定义一个参数 // 如果定义多个则抛出错误 try { userBean = userMapper.getUserByName5(argBean, 1); System.out.println(userBean); } catch (Exception e) { System.out.println(e.getMessage()); } userBean = userMapper.getUserByName6(2); System.out.println(userBean); } }