Mybatis面试系列六

1、Mybatis 动态sql有什么用?执行原理?有哪些动态sql?

Mybatis 动态 sql 可以在 Xml 映射文件内,以标签的形式编写动态 sql,执行原理

是根据表达式的值完成逻辑判断并动态拼接sql的功能。

Mybatis 提供了 9种动态 sql标签:trim | where | set | foreach | if | choose

| when | otherwise | bind。

2、Xml映射文件中,除了常见的select|insert|updae|delete

标签之外,还有哪些标签?

答:

复制代码
<resultMap>、<parameterMap>、<sql>、<include>、
<selectKey>

,加上动态 sql 的 9 个标签,其中<sql>为 sql 片段标签,通过
<include>标签引入 sql 片段,<selectKey>为不支持自增的主键生成策略标

签。

3、Mybatis 的 Xml 映射文件中,不同的 Xml映射文件,id是否可以重复?

不同的Xml映射文件,如果配置了namespace,那么 id可以重复;如果没有配

置 namespace,那么 id 不能重复;

原因就是namespace+id 是作为 Map<String, MapperStatement>的 key

使用的,如果没有namespace,就剩下 id,那么,id重复会导致数据互相覆盖。

有了namespace,自然 id 就可以重复,namespace 不同,namespace+id 自然

也就不同。

4、为什么说Mybatis是半自动ORM映射工具?它与全自动

的区别在哪里?

Hibernate 属于全自动 ORM 映射工具,使用 Hibernate 查询关联对象或者关联

集合对象时,可以根据对象关系模型直接获取,所以它是全自动的。而Mybatis

在查询关联对象或关联集合对象时,需要手动编写sql来完成,所以,称之为半自

动 ORM映射工具。

5、 一对一、一对多的关联查询 ?

复制代码
<mapper namespace="com.lcb.mapping.userMapper">
 <!--association 一对一关联查询-->
 <select id="getClass" parameterType="int"
 resultMap="ClassesResultMap">
 select * from class c,teacher t where c.teacher_id=t.t_id and 
 c.c_id=#{id}
 </select>
 <resultMap type="com.lcb.user.Classes" id="ClassesResultMap">
 <!--实体类的字段名和数据表的字段名映射-->
 <id property="id" column="c_id"/>
 <result property="name" column="c_name"/>
 <association property="teacher" 
 javaType="com.lcb.user.Teacher">
 <id property="id" column="t_id"/>
 <result property="name" column="t_name"/>
 </association>
 </resultMap>
 <!--collection一对多关联查询-->
 <select id="getClass2" parameterType="int" 
 resultMap="ClassesResultMap2">
 select * from class c,teacher t,student s where c.teacher_id=t.t_id 
 and c.c_id=s.class_id and c.c_id=#{id}
 </select>
 <resultMap type="com.lcb.user.Classes" id="ClassesResultMap2">
 <id property="id" column="c_id"/>
 <result property="name" column="c_name"/>
 <association property="teacher" 
 javaType="com.lcb.user.Teacher">
 <id property="id" column="t_id"/>
<result property="name" column="t_name"/>
 </association>
 <collection property="student" 
 ofType="com.lcb.user.Student">
 <id property="id" column="s_id"/>
 <result property="name" column="s_name"/>
 </collection>
 </resultMap>
 </mapper>

阿里云618精选云产品限量热卖,助力低成本上云

复制代码
相关推荐
触底反弹11 小时前
🔥 2026 大模型选择指南:别再只看 Benchmark 了,这些维度才是关键!
人工智能·面试
醇氧13 小时前
CountDownLatch / CyclicBarrier / Semaphore 面试高频问答清单
前端·面试·职场和发展
黄敬峰16 小时前
从零搞懂 useState 与 Fragment:React 函数式组件的基石
面试
Android研究员20 小时前
Android进阶之事件分发机制深度剖析
android·前端·面试
触底反弹20 小时前
🔥 AI 写代码总翻车?这套实战方法论救了我
人工智能·面试·程序员
风栖柳白杨20 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试
风栖柳白杨1 天前
【面试】职位要求_准备
面试·职场和发展
Assby1 天前
为什么我不建议你在 MySQL 里写 `IN (超过1000个ID)`?从 AST 解析到存储引擎的深度拆解
后端·面试
触底反弹2 天前
🚀 从 DOM0 级到 React 合成事件:前端事件监听的 20 年演进史
前端·react.js·面试
kyriewen2 天前
我给前端项目的接口请求套了6层保护——才发现以前一直在裸奔
前端·javascript·面试