一、查询返回Map
场景: 当查询返回的列不固定,即没有现成类可以封装数据时,可以使用Map来存储数据
注意: 一行数据用一个Map封装
演示1: selectOne 查询一个,用Map封装
演示2: selectAll 查询全部,用List
二、主键回填
两表有关联,例如用户和订单
下订单,向数据库插入订单,但是用户表也需要更新或者插入订单编号
即 A表数据插入后,B表中需要A表刚才插入的ID
主键回填?
回忆: 插入时Controller->Service->Mapper方法的参数列表都是对象,例如save(User user),但是这个属性中id是没有值,数据库插入时不插入id,id是自增的
回填就是指: 当你插入完后,这个user对象中id属性有值了, 这就是mybatis将id值回填都对象
只需要在正常的插入的sql中加一段
<!--
keyProperty 是要回填的对象的主键的属性
order是执行顺序
resultType 是主键的数据类型
-->
<selectKey keyProperty="id" order="AFTER" resultType="int">
select last_insert_id()
</selectKey>
完整代码如下
<!--新增所有列-->
<insert id="insert" keyProperty="userId" useGeneratedKeys="true">
insert into sys_user(user_name, nick_name, user_type, email, phonenumber, sex, avatar, password, status, del_flag, login_ip, login_date, create_by, create_time, update_by, update_time, remark)
values (#{userName}, #{nickName}, #{userType}, #{email}, #{phonenumber}, #{sex}, #{avatar}, #{password}, #{status}, #{delFlag}, #{loginIp}, #{loginDate}, #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{remark})
<!-- 主键回填 -->
<selectKey keyProperty="userId" order="AFTER" resultType="long">
select last_insert_id()
</selectKey>
</insert>