映射与传参 - MyBatis 面试题及答案
2025/12/19大约 4 分钟
返回MyBatis 面试题索引 第 2/5 章
4.在mapper中如何传递多个参数?

方法1:顺序传参法
public User selectUser(String name, int deptId); <select id="selectUser" resultMap="UserResultMap">
select * from user
where user_name = #{0} and dept_id = #{1}
</select>- #{}里面的数字代表传入参数的顺序。
- 这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。
方法2:@Param注解传参法
public User selectUser(@Param("userName") String name, int @Param("deptId") deptId); <select id="selectUser" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>- #{}里面的名称对应的是注解@Param括号里面修饰的名称。
- 这种方法在参数不多的情况还是比较直观的,(推荐使用)。
方法3:Map传参法
public User selectUser(Map<String, Object> params); <select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>- #{}里面的名称对应的是Map里面的key名称。
- 这种方法适合传递多个参数,且参数易变能灵活传递的情况。
方法4:Java Bean传参法
public User selectUser(User user); <select id="selectUser" parameterType="com.jourwon.pojo.User" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>- #{}里面的名称对应的是User类里面的成员属性。
- 这种方法直观,需要建一个实体类,扩展不容易,需要加属性,但代码可读性强,业务逻辑处理方便,推荐使用。(推荐使用)。
5.实体类属性名和表中字段名不一样 ,怎么办?
第1种: 通过在查询的SQL语句中定义字段名的别名,让字段名的别名和实体类的属性名一致。
<select id="getOrder" parameterType="int" resultType="com.jourwon.pojo.Order"> select order_id id, order_no orderno ,order_price price form orders where order_id=#{id}; </select>第2种: 通过resultMap 中的
<result>来映射字段名和实体类属性名的一一对应的关系。<select id="getOrder" parameterType="int" resultMap="orderResultMap"> select * from orders where order_id=#{id} </select> <resultMap type="com.jourwon.pojo.Order" id="orderResultMap"> <!–用id属性来映射主键字段–> <id property="id" column="order_id"> <!–用result属性来映射非主键字段,property为实体类属性名,column为数据库表中的属性–> <result property ="orderno" column ="order_no"/> <result property="price" column="order_price" /> </reslutMap>
6.Mybatis是否可以映射Enum枚举类?
- Mybatis当然可以映射枚举类,不单可以映射枚举类,Mybatis可以映射任何对象到表的一列上。映射方式为自定义一个TypeHandler,实现TypeHandler的setParameter()和getResult()接口方法。
- TypeHandler有两个作用,一是完成从javaType至jdbcType的转换,二是完成jdbcType至javaType的转换,体现为setParameter()和getResult()两个方法,分别代表设置sql问号占位符参数和获取列查询结果。
7.#{}和${}的区别?

- #{}是占位符,预编译处理;${}是拼接符,字符串替换,没有预编译处理。
- Mybatis在处理#{}时,#{}传入参数是以字符串传入,会将SQL中的#{}替换为?号,调用PreparedStatement的set方法来赋值。
- #{} 可以有效的防止SQL注入,提高系统安全性;${} 不能防止SQL 注入
- #{} 的变量替换是在DBMS 中;${} 的变量替换是在 DBMS 外
8.模糊查询like语句该怎么写?

- 1 ’%${question}%’ 可能引起SQL注入,不推荐
- 2 "%"#{question}"%" 注意:因为#{…}解析成sql语句时候,会在变量外侧自动加单引号’ ',所以这里 % 需要使用双引号" ",不能使用单引号 ’ ',不然会查不到任何结果。
- 3 CONCAT(’%’,#{question},’%’) 使用CONCAT()函数,(推荐✨)
- 4 使用bind标签(不推荐)
<select id="listUserLikeUsername" resultType="com.jourwon.pojo.User">
<bind name="pattern" value="'%' + username + '%'" />
select id,sex,age,username,password from person where username LIKE #{pattern}
</select>最近建一些几十个工作内推群,各大城市都有,群里目前已经收集了很多内推岗位,大厂、中厂、小厂、外包都有。 欢迎HR、开发、测试、运维和产品加入。

扫描下方微信,备注:网站+所在城市,即可拉你进工作内推群。
