mybatis实战提升(关于各种属性的详解)
一:属性讲解
1.默认配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="study.dao.StudentDao">
</mapper>
2.namespace的讲解
namespace属性:用于指定当前的映射文件和那个接口进行映射,需要知道那个接口的文件路径,需要标注包的完整路径接口
3.resultMap和resultType讲解
<select id="findByUsername" resultMap="UserEntityMap">
SELECT * FROM t_user username = #{username}
</select>
resultType:表示查询的结果集类型,只需要指定对应映射类的类型,并且包含完整包接口: resultType="com.example.store.entity.User
resultMap: 表示当表的字段和类的对象属性的字段名称不一致值,来自定义映射规则
(由于实体类中采用了驼峰命名方式,导致实体类中的字段名和数据库中的列名不一致,需要自定义映射规则)
4.自定义映射规则resultMap
在定义映射规则时主键是不可以省略的<result column="uid" property="uid"></result>
<!-- id属性:标签给这个映射负责分配一个唯一的id值,对应的就是resultMap=“id"的属性的取值-->
<!-- type属性:取值是一个类,表示的是数据库中的查询结果与java中那个实体类进行结果映射-->
<resultMap id="UserEntityMap" type="com.example.store.entity.User">
<!-- 将表的资源和类的睡醒不一样的字段进行匹配指定,名称一直的字段可以省略不写-->
<!--
配合完成名称不一致的映射
column属性:表示表中的资源名称
property属性:表示类中的属性名称
-->
<!-- 在定义映射规则时主键是不可以省略的-->
<result column="uid" property="uid"></result>
<result column="is_delete" property="isDelete"/>
<result column="created_user" property="createdUser"/>
<result column="created_time" property="createdTime"></result>
<result column="modified_user" property="modifiedUser"></result>
<result column="modified_time" property="modifiedTime"></result>
</resultMap>
5.useGeneratedKeys的意义
useGeneratedKeys属性:开启某个键的值的递增(主键设置为递增
keyProperty属性:标签将表中的那个字段作为主键进行递增
<insert id="insert" useGeneratedKeys="true" keyProperty="uid">
INSERT INTO t_user(username, salt, phone, email,
gender, avatar, is_delete,
created_user, created_time,
modified_user, modified_time)
values (
#{username}, #{salt}, #{phone}, #{email},
#{gender}, #{avatar}, #{isDelete},
#{createdUser}, #{createdTime},
#{modifiedUser}, #{modifiedTime})
</insert>
6.mybatis中的if标签
mybatis中的if标签通常用来判断是否为空
if表示条件判断标签,test接收的是一个返回值为boolean类型的条件,如果test条件结果为true则执行if标签内部的语句
<update id="updateInfoByUid">
-- if表示条件判断标签,test接收的是一个返回值为boolean类型的条件,如果test条件结果为true则执行if标签内部的语句
UPDATE t_user SET
<if test="phone!=null and phone != ''">phone = #{phone},</if>
<if test="email!=null and phone != ''">email = #{email},</if>
<if test="gender!=null and gender != ''">gender = #{gender},</if>
<if test="modified_user!=null and modified_user !=''">modified_user = #{modifiedUser},</if>
<if test="modified_time!=null and modified_time !=''">modified_time = #{modifiedTime}</if>
WHERE uid = #{uid}
</update>