mybatis标签使用及场景
主键返回
<insert id="insertUser" parameterType="com.kkb.mybatis.po.User">
<!-- selectKey将主键返回,需要再返回 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});
</insert>
添加selectKey标签实现主键返回。
- keyProperty:指定返回的主键,存储在pojo中的哪个属性
- order:selectKey标签中的sql的执行顺序,是相对与insert语句来说。由于mysql的自增原理,执 行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after
- resultType:返回的主键对应的JAVA类型
- LAST_INSERT_ID():是mysql的函数,返回auto_increment自增列新记录id值。
关联查询(一对一)
<!-- 查询订单关联用户信息使用resultmap -->
<resultMap type="OrdersExt" id="ordersAndUserRstMap">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- 一对一关联映射 -->
<!--property:Orders对象的user属性javaType:user属性对应 的类型-->
<association property="user" javaType="com.kkb.mybatis.po.User">
<!-- column:user表的主键对应的列 property:user对象中id属性-->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findOrdersAndUserRstMap" resultMap="ordersAndUserRstMap">
SELECT
o.id,
o.user_id,
o.number,
o.createtime,
o.note,
u.username,
u.address
FROM
orders o
JOIN `user` u ON u.id = o.user_id
</select>
标签属性:
- association:表示进行一对一关联查询映射
- property:表示关联查询的结果存储在com.kkb.mybatis.po.Orders的user属性中
- javaType:表示关联查询的映射结果类型
关联查询(一对多)
<resultMap type="user" id="userAndOrderRstMap">
<!-- 用户信息映射 -->
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
<!-- 一对多关联映射 -->
<collection property="orders" ofType="orders">
<id property="id" column="oid"/>
<result property="userId" column="id"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
</collection>
</resultMap>
<select id="findUserAndOrderRstMap" resultMap="userAndOrderRstMap">
SELECT
u.*,
o.id oid,
o.number,
o.createtime,
o.note
FROM
`user` u
LEFT JOIN orders o ON u.id = o.user_id
</select>
标签属性:
- Collection标签:定义了一对多关联的结果映射
- property="orders"**:关联查询的结果集存储在User对象的上哪个属性
- ofType="orders"**:指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也 可以使用全限定名。