16- Mybatis如何实现多表查询
Mybatis是新多表查询的方式也有二种 :
第一种是 : 编写多表关联查询的SQL语句 , 使用ResultMap建立结果集映射 , 在ResultMap中建立多表结果集映射的标签有association和collection
<resultMap id="Account_User_Map" type="com.heima.entity.Account"> <id property="id" column="id"></id> <result property="uid" column="uid"></result> <result property="money" column="money"></result> <association property="user"> <id property="id" column="uid"></id> <result property="username" column="username"></result> <result property="birthday" column="birthday"></result> <result property="sex" column="sex"></result> <result property="address" column="address"></result> </association> </resultMap> <!--public Account findByIdWithUser(Integer id);--> <select id="findByIdWithUser" resultMap="Account_User_Map"> select a.*, username, birthday, sex, address from account a , user u where a.UID = u.id and a.ID = #{id} ; </select>
第二种是 : 将多表查询分解为多个单表查询, 使用ResultMap表的子标签association和collection标签的select属性指定另外一条SQL的定义去执行, 然后执行结果会被自动封装
<resultMap id="Account_User_Map" type="com.heima.entity.Account" autoMapping="true"> <id property="id" column="id"></id> <association property="user" select="com.heima.dao.UserDao.findById" column="uid" fetchType="lazy"></association> </resultMap> <!--public Account findByIdWithUser(Integer id);--> <select id="findByIdWithUser" resultMap="Account_User_Map"> select * from account where id = #{id} </select>
17-Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?
Mybatis动态sql可以让我们在Xml映射文件内,以标签的形式编写动态sql,完成逻辑判断和动态 拼接sql的功能,Mybatis提供了9种动态sql标签 trim|where|set|foreach|if|choose|when|otherwise|bind。
其执行原理为,使用OGNL从sql参数对象中计算表达式的值,根据表达式的值动态拼接sql,以此 来完成动态sql的功能。
18- Mybatis是否支持延迟加载?
Mybatis仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是 一对一,collection指的就是一对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载 lazyLoadingEnabled=true|false。
19- 如何使用Mybatis实现批量插入 ?
使用foreach标签 , 它可以在SQL语句中进行迭代一个集合。foreach标签的属性主 要有item,index,collection,open,separator,close。
- collection : 代表要遍历的集合 ,
- item 表示集合中每一个元素进行迭代时的别名,随便起的变量名;
- index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置,不常用;
- open 表示该语句以什么开始
- separator 表示在每次进行迭代之间以什么符号作为分隔符
- close 表示以什么结束
20- Mybatis 批量插入是否能够返回主键
可以, 返回的主键在传入集合的每个对象属性中封装的