Mybatis常用标签

1. 定义sql语句

1.1 select 标签

属性介绍:

id :唯一的标识符.
parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user
resultType:语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与resultMap 不能并用)

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
        select * from student where id=#{id}
</select>

1.2 insert标签

属性介绍:

id :唯一的标识符
parameterType:传给此语句的参数的全路径名或别名

    <insert id="insertUser" parameterType="User">
            <!-- 主键回填,将新数据的ID,存入java对象的和主键对应的属性中 -->
            <selectKey order="AFTER" resultType="int" keyProperty="id">
                select last_insert_id()
            </selectKey>
        insert into t_user values(#{id},#{username},#{password},#{gender},#{registTime})
    </insert>

1.3 delete标签

属性同 insert

<delete id="deleteByPrimaryKey" parameterType="Object">
        delete from student where id=#{id}
</delete>

1.4 update标签

属性同 insert

2. 配置JAVA对象属性与查询结果集中列名对应关系

resultMap 标签的使用

基本作用
建立SQL查询结果字段与实体属性的映射关系信息
查询的结果集转换为java对象,方便进一步操作。
将结果集中的列与java对象中的属性对应起来并将值填充进去

注意:与java对象对应的列不是数据库中表的列名,而是查询后结果集的列名

<resultMap id="BaseResultMap" type="com.online.charge.platform.student.model.Student">
        <id property="id" column="id" />
        <result column="NAME" property="name" />
        <result column="HOBBY" property="hobby" />
        <result column="MAJOR" property="major" />
        <result column="BIRTHDAY" property="birthday" />
        <result column="AGE" property="age" />

</resultMap>
  <!--查询时resultMap引用该resultMap -->  
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
        select id,name,hobby,major,birthday,age from student where id=#{id}
</select> 

标签说明:

  • 主标签:
    id:该resultMap的标志
    type:返回值的类名,此例中返回Studnet类

  • 子标签:
    id:用于设置主键字段与领域模型属性的映射关系,此处主键为ID,对应id。
    result:用于设置普通字段与领域模型属性的映射关系

3. 动态sql拼接

3.1 if 标签

if标签通常用于WHERE语句、UPDATE语句、INSERT语句中,通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。

<if test="name != null and name != ''">
         and NAME = #{name}
</if>

3.2 foreach 标签

foreach标签主要用于构建in条件,可在sql中对集合进行迭代。也常用到批量删除、添加等操作中。

 <!-- in查询所有,不分页 -->
    <select id="selectIn" resultMap="BaseResultMap">
        select name,hobby 
              from student where id in
        <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

属性介绍:

collection:collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合。
item :表示在迭代过程中每一个元素的别名
index :表示在迭代过程中每次迭代到的位置(下标)
open :前缀
close :后缀
separator :分隔符,表示迭代时每个元素之间以什么分隔

3.3 choose标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。

if是与(and)的关系,而choose是或(or)的关系。

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">     
    SELECT * from STUDENT WHERE 1=1    
    <where>     
        <choose>     
            <when test="Name!=null and student!='' ">     
                   AND name LIKE CONCAT(CONCAT('%', #{student}),'%')      
            </when>     
            <when test="hobby!= null and hobby!= '' ">     
                    AND hobby = #{hobby}      
            </when>                   
            <otherwise>     
                    AND AGE = 15  
            </otherwise>     
        </choose>     
    </where>     
</select>   

4. 格式化输出

4.1 where标签

当if标签较多时,这样的组合可能会导致错误。 如下:

<select id="getStudentListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from STUDENT      
        WHERE      
        <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{name}),'%')      
        </if>     
        <if test="hobby!= null and hobby!= '' ">     
            AND hobby = #{hobby}      
        </if>     
</select> 

当name值为null时,查询语句会出现 “WHERE AND” 的情况,解决该情况除了将"WHERE"改为“WHERE 1=1”之外,还可以利用where标签。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

<select id="getStudentListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from STUDENT      
       <where>   
         <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{name}),'%')      
         </if>     
         <if test="hobby!= null and hobby!= '' ">     
            AND hobby = #{hobby}      
         </if>  
       </where>        
</select>    

4.2 set 标签

没有使用if标签时,如果有一个参数为null,都会导致错误。当在update语句中使用if标签时,如果最后的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置set关键字,和剔除追加到条件末尾的任何不相关的逗号。

<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT   
       SET NAME = #{name},   
           MAJOR = #{major},
           HOBBY = #{hobby}
     WHERE ID = #{id};      
</update>   
<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT SET    
        <if test="name!=null and name!='' ">     
            NAME = #{name},      
        </if>     
        <if test="hobby!=null and hobby!='' ">     
            MAJOR = #{major},      
        </if> 
        <if test="hobby!=null and hobby!='' ">     
            HOBBY = #{hobby}    
        </if>          
    WHERE ID = #{id};      
</update>  

使用set+if标签修改后,如果某项为null则不进行更新,而是保持数据库原值。

<update id="updateStudent" parameterType="Object">     
    UPDATE STUDENT      
    <set>     
        <if test="name!=null and name!='' ">     
            NAME = #{name},      
        </if>     
        <if test="hobby!=null and hobby!='' ">     
            MAJOR = #{major},      
        </if> 
        <if test="hobby!=null and hobby!='' ">     
            HOBBY = #{hobby}    
        </if>     
    </set>     
    WHERE ID = #{id};      
</update>  

4.3 trim标签

格式化输出,也可以通过trim标签设定或忽略前后缀来实现

5. 配置关联关系

5.1 collection标签

集合,用于一对多

<mapper namespace="com.qf.dao.DepartmentDAO">
    <resultMap id="dept_emp" type="Department">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="location" property="location"></result>

        <!-- emp_id  emp_name  salary    employees -->
        <collection property="employees" ofType="Employee">
            <id column="emp_id" property="id"></id>
            <result column="emp_name" property="name"></result>
            <result column="salary" property="salary"></result>
        </collection>
    </resultMap>
    <select id="queryDepartmentById" resultMap="dept_emp">
        select t_departments.id ,t_departments.name,t_departments.location,
               t_employees.id emp_id,t_employees.name emp_name,t_employees.salary
        from t_departments join t_employees
        on t_departments.id = t_employees.dept_id
        where t_departments.id=#{id}
    </select>
</mapper>

5.2 association标签

关联,用于一对一

<mapper namespace="com.qf.dao.EmployeeDAO">
    <resultMap id="emp_dept" type="Employee">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="salary" property="salary"></result>

        <association property="department" javaType="Department">
            <id column="deptId" property="id"></id>
            <result column="deptName" property="name"></result>
            <result column="location" property="location"></result>
        </association>
    </resultMap>

    <select id="queryEmployeeById" resultMap="emp_dept">
        select t_employees.id,t_employees.name,t_employees.salary,
               t_departments.id deptId ,t_departments.name deptName,t_departments.location

        from t_employees join t_departments
        on t_departments.id = t_employees.dept_id
        where t_employees.id=#{id}
    </select>
</mapper>

6. 定义常量及引用

6.1 sql标签

当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。为求结构清晰也可将sql语句分解。

<!-- 查询字段 -->
    <sql id="Base_Column_List">
        ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY
    </sql>

 <!-- 查询条件 -->
    <sql id="Example_Where_Clause">
        where 1=1
        <trim suffixOverrides=","> 
            <if test="id != null and id !=''">
                and id = #{id}
            </if>
            <if test="major != null and major != ''">
                and MAJOR = #{major}
            </if>
            <if test="birthday != null ">
                and BIRTHDAY = #{birthday}
            </if>
            <if test="age != null ">
                and AGE = #{age}
            </if>
            <if test="name != null and name != ''">
                and NAME = #{name}
            </if>
            <if test="hobby != null and hobby != ''">
                and HOBBY = #{hobby}
            </if>            
            <if test="sorting != null">
                order by #{sorting}
            </if>
            <if test="sort!= null  and sort != '' ">
                order by ${sort}   ${order}
            </if>

        </trim>
    </sql>

6.2 include标签

用于引用定义的常量

<!-- 查询所有,不分页 -->
    <select id="selectAll" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM
        student
        <include refid="Example_Where_Clause" />
    </select>

<!-- 分页查询 -->
    <select id="select" resultMap="BaseResultMap">

        select * from (
            select tt.*,rownum as rowno from 
                (
                    SELECT
                    <include refid="Base_Column_List" /> 
                    FROM
                    student
                    <include refid="Example_Where_Clause" />
                     ) tt 
                     <where>
                            <if test="pageNum != null and rows != null">
                            and  rownum  <![CDATA[<=]]>#{page}*#{rows}
                         </if>
                    </where>
             ) table_alias
            where table_alias.rowno>#{pageNum}

    </select>
<!-- 根据条件删除 -->
    <delete id="deleteByEntity" parameterType="java.util.Map">
    DELETE  FROM   student
    <include refid="Example_Where_Clause" />
    </delete>

转载于:https://blog.csdn.net/weixin_44117767/article/details/103767339

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容