Mybatis 如何获取生成的主键
我知道的有二种方式
- 在insert标签上, 使用useGeneratedKeys="true" 和 keyProperty="userId"
- 在insert表内部, 使用 selectKey标签 , 里面使用select last_insert_id()查询生成的ID返回
当实体类中的属性名和表中的字段名不一样 ,怎么办
第1种: 通过在查询的SQL语句中定义字段名的别名,让字段名的别名和实体类的属性名一致。
第2种: 通过 ResultMap来映射字段名和实体类属性名
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>
Mybatis是否支持延迟加载?
Mybatis仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是 一对一,collection指的就是一对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载 lazyLoadingEnabled=true|false。
如何使用Mybatis实现批量插入 ?
使用foreach标签 , 它可以在SQL语句中进行迭代一个集合。foreach标签的属性主 要有item,index,collection,open,separator,close。
- collection : 代表要遍历的集合 ,
- item 表示集合中每一个元素进行迭代时的别名,随便起的变量名;
- index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置,不常用;
- open 表示该语句以什么开始
- separator 表示在每次进行迭代之间以什么符号作为分隔符
- close 表示以什么结束
Mybatis 批量插入是否能够返回主键
可以, 返回的主键在传入集合的每个对象属性中封装的