Mybatis常问面试题
- 自动生成还是手写
自动生成和手写SQL都应用- mybatis-generator.jar
自动生成:主要生成一些基本的增删改查,生成一些简单的配置 - 手写:主要解决一些复杂的查询情况,多表查询,条件查询
- mybatis-generator.jar
- #和$的区别?
- #{}内部使用预编译PreparedStatement机制执行SQL,支持?占位符,可以防止SQL注入;
insert into user(id, name, age) value(?, ?, ?)
insert into user(id, name, age) value(#{id}, #{name}, #{age})
- ${}内部采用S参数只能statement机制将参数和SQL拼装在一起,不支持?占位符,作为拼接;
- 如果是动态表名或字段名
select * from ${tableName} where date = #{date}
- like ‘’位置,建议使用${}
select * from user where name like ‘% ${name} %’
能用#{}就最好不要用${}
- namespace标签
对应的是mapper关系映射
- sql的动态标签有哪些?
trim、here、set、foreach、if、choose、when、otherwise、bind
<trim prefix="WHERE" prefixOverrides="AND">
where
<if test="name != null and name != ' '">
name = #{name }
</if>
<if test="age!= null and age!= ' '">
AND age like #{age}
</if>
</trim>
<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
#{item.id}
</foreach>
5.插入一条数据,获得它的主键
<insert>
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
6.如何传入多个字段进行查询
- 传入一个对象,将需要传入的字段赋值到对象中
- 传入一个Map,将数据封装到map
- 直接在mapper传参是直接Param(), parameterType就可以不用写了
- 还没想到…
这是目前遇到的一些情况,后续再添加和更新…
如有不对的地方,烦请告知,及时改正