【SQL用法】Mybatis框架中的xml文件中经常使用的sql语句

简介: 【SQL用法】Mybatis框架中的xml文件中经常使用的sql语句

项目中经常会用到的sql语句有:

一、insert语句

<!--保存用户信息-->
<insert id="save">
        insert into mainsite_product_message
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="customerName != null and customerName != ''">
                customer_name,
            </if>
            <if test="customerPhone != null and customerPhone != ''">
                customer_phone,
            </if>
            <if test="customerEmail != null and customerEmail != ''">
                customer_email,
            </if>
            <if test="createTime != null">
                create_time,
            </if>
            <if test="customerStatus != null and customerStatus != ''">
                customer_status,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="customerName != null and customerName != ''">
                #{customerName},
            </if>
            <if test="customerPhone != null and customerPhone != ''">
                #{customerPhone},
            </if>
            <if test="customerEmail != null and customerEmail != ''">
                #{customerEmail},
            </if>
            <if test="createTime != null">
                #{createTime},
            </if>
            <if test="customerStatus != null and customerStatus != ''">
                #{customerStatus},
            </if>
        </trim>
    </insert>
    <!--修改用户信息-->
    <update id="update">
    </update>
    <!--批量更改客户状态-->
    <update id="updateStatus">
        update mainsite_product_message set customer_status = 1 where id in
        <foreach collection="array" item="id" open="(" separator="," close=")" index="index">
            #{id}
        </foreach>
    </update>
    <!--根据主键删除留言,物理删除-->
    <delete id="deleteByPrimaryKey">
        delete from mainsite_product_message where id = #{id}
    </delete>
    <!--查询留言列表-->
    <select id="selectByCondition"
            resultType="com.uiotsoft.mainsite.module.productmessage.entity.ProductMessage">
        select
        id as id,
        site_id as siteId,
        site_name as siteName,
        customer_name as customerName,
        customer_phone as customerPhone,
        customer_email as customerEmail,
        product_want as productWant,
        create_time as createTime,
        customer_status as customerStatus,
        search_keyword as searchKeyword
        from mainsite_product_message
        <trim prefix="WHERE (" suffix=")" prefixOverrides="AND|OR">
            <if test="customerName != null and customerName != ''">
                customer_name like CONCAT('%', #{customerName}, '%')
            </if>
            <if test="customerPhone != null and customerPhone != ''">
                and customer_phone = #{customerPhone}
            </if>
            <if test="createTime != null">
                and create_time = #{createTime}
            </if>
            <if test="customerEmail != null and customerEmail != ''">
                and customer_email = #{customerEmail}
            </if>
            <if test="productWant != null and productWant != ''">
                and product_want = #{productWant}
            </if>
            <if test="siteId != null and siteId != '' and siteId != 1">
                and site_id = #{siteId}
            </if>
            <if test="siteName != null and siteName != ''">
                and site_name = #{siteName}
            </if>
            <if test="customerStatus != null and customerStatus != ''">
                and customer_status = #{customerStatus}
            </if>
            <if test="searchKeyword != null and searchKeyword != ''">
                and search_keyword = #{searchKeyword}
            </if>
        </trim>
        ORDER BY create_time DESC
    </select>

<trim><choose><when></when><otherwise></otherwise></choose></trim>

二、select查询语句

<select id="selectByContentListBySiteIdAndCategoryIds"   resultType="java.util.Map">
        SELECT
        c.*,
        m.*,
        u.avatar avatar,
        u.username username
        FROM
        site_model_content c LEFT JOIN  site_model_${tableName}  m
        ON
        c.content_id = m.content_id
        LEFT JOIN
        t_sys_user u ON u.user_id = c.user_id
        <trim prefix="WHERE ("  suffix=")" prefixOverrides="AND|OR">
            c.status=1
            <if test="siteId!=null">
               AND  c.site_id = #{siteId}
            </if>
            <if test="categoryIds!=null">
               AND
                c.category_id in
                 <foreach item="item" index="index" collection="categoryIds" open="(" separator="," close=")">
                   #{item}
                 </foreach>
            </if>
            <if test='isRecommend!=null and isRecommend==1'>
                AND
                c.recommend = 1
            </if>
            <if test='whereParam!=null and valueParam!=null'>
                AND  m.${whereParam} = #{valueParam}
            </if>
            <if test='isPic!=null and isPic==1'>
                AND
                c.thumb!=''
            </if>
            <if test='isPic!=null and isPic==0'>
                AND
                c.thumb=''
            </if>
            <if test='siteType!=null'>
                AND
                c.site_type like CONCAT('%', #{siteType}, '%')
            </if>
        </trim>
        <choose>
            <when test="orderBy==1">
                order by c.content_id
            </when>
            <when test="orderBy==2">
                order by c.inputdate DESC
            </when>
            <when test="orderBy==3">
                order by c.inputdate
            </when>
            <when test="orderBy==4">
                order by c.updatedate DESC
            </when>
            <when test="orderBy==5">
                order by c.updatedate
            </when>
            <when test="isHot==1">
                order by c.view_num DESC
            </when>
            <otherwise>
                order by c.content_id DESC
            </otherwise>
        </choose>
    </select>

三、批量添加

<!-- 批量添加 -->
    <insert id="insertMore" useGeneratedKeys="true" keyProperty="siteId">
        INSERT INTO
            t_cms_site(
            site_name,
            `domain`,
            template,
            is_mobile,
            mobile_tpl,
            status
            )
            values
            <foreach item="item" collection="list" separator=",">
                (#{item.siteName},#{item.domain},#{item.template},
                #{item.isMobile},#{item.mobileTpl},#{item.status})
            </foreach>
    </insert>

四、与时间比较相关的

SELECT
        count(*)
        FROM
        crm_contract
        <where> isDel = 0
            <if test="departmentId != null and departmentId != null">
                and departmentId LIKE CONCAT(#{departmentId},'%')
            </if>
            <if test="directorAccount != null and directorAccount !='' ">
                and directorAccount = #{directorAccount}
            </if>
            <if test="executeState != null and executeState != ''">
                and executeState = #{executeState}
            </if>
            <if test="auditState != null and auditState != ''">
                and auditState = #{auditState}
            </if>
            <if test="contractType != null and contractType != ''">
                and contractType = #{contractType}
            </if>
            <if test="categoryId != null and categoryId != ''">
                and categoryId = #{categoryId}
            </if>
            <if test="customerName != null and customerName != ''">
                and customerName like CONCAT("%",#{customerName},"%")
            </if>
            <if test="director != null and director != ''">
                and director like CONCAT("%",#{director},"%")
            </if>
            <if test="signUser != null and signUser != ''">
                and signUser like CONCAT("%",#{signUser},"%")
            </if>
            <if test="startDate != null">
                <![CDATA[ and DATE_FORMAT(endDate,"%Y-%m-%d")  >= DATE_FORMAT(#{startDate},"%Y-%m-%d") ]]>
            </if>
            <if test="endDate != null">
                <![CDATA[ and DATE_FORMAT(endDate,"%Y-%m-%d")  <= DATE_FORMAT(#{endDate},"%Y-%m-%d")]]>
            </if>
        </where>


        select
        c.*
        from crm_contract c left join crm_customer_info i on c.customerId =
        i.customerId
        <where>
            c.isDel = 0
            <if test="startDate != null and startDate != ''">
                and c.endDate &gt;= #{startDate}
            </if>
            <if test="endDate != null and endDate != ''">
                and c.endDate &lt;= #{endDate}
            </if>
            <if test="customerName != null and customerName != ''">
                and c.customerName like CONCAT(#{customerName},"%")
            </if>
            <if test="director != null and director != ''">
                and c.director like CONCAT(#{director},"%")
            </if>
            <if test="auditState != null and auditState != ''">
                and c.auditState = #{auditState}
            </if>
        </where>
        limit #{start},#{end}
 <select id="selectAll" resultType="java.util.Map">
        SELECT
        log_id AS logId,
        page_name AS pageName,
        template_name AS templateName,
        publish_status AS publishStatus,
        consuming_time AS consumingTime,
        C.description,
        create_time AS createTime,
        C.site_id AS siteId,
        C.category_id AS categoryId,
        C.site_name as siteName,
        D.category_name as categoryName
        FROM
            (
                SELECT
                    log_id,
                    page_name,
                    template_name,
                    publish_status,
                    consuming_time,
                    A.description,
                    create_time,
                    A.site_id,
                    category_id,
                    site_name
                FROM
                    mainsite_publish_log A
                LEFT JOIN t_cms_site B ON A.site_id = B.site_id
            ) C
        LEFT JOIN t_cms_category D ON (C.category_id = D.category_id)
        <where>
            <if test="startTime != null">
                <![CDATA[ and DATE_FORMAT(create_time,"%Y-%m-%d %H:%i:%s")  >= DATE_FORMAT(#{startTime},"%Y-%m-%d %H:%i:%s") ]]>
            </if>
            <if test="endTime != null">
                <![CDATA[ and DATE_FORMAT(create_time,"%Y-%m-%d %H:%i:%s")  <= DATE_FORMAT(#{endTime},"%Y-%m-%d %H:%i:%s") ]]>
            </if>
        </where> order by log_id desc
    </select>

 

拓展:

Mysql动态SQL语句标签:https://blog.csdn.net/weixin_44299027/article/details/103258305

 

 

 

完结!


相关文章
SQL XML Java
279 0
|
7月前
|
SQL Java 数据库连接
区分iBatis与MyBatis:两个Java数据库框架的比较
总结起来:虽然从技术角度看,iBATIS已经停止更新但仍然可用;然而考虑到长期项目健康度及未来可能需求变化情况下MYBATISS无疑会是一个更佳选择因其具备良好生命周期管理机制同时也因为社区力量背书确保问题修复新特征添加速度快捷有效.
588 12
|
8月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
483 18
|
8月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
319 0
|
8月前
|
SQL XML Java
MyBatis框架如何处理字符串相等的判断条件。
总的来说,MyBatis框架提供了灵活而强大的机制来处理SQL语句中的字符串相等判断条件。无论是简单的等值判断,还是复杂的条件逻辑,MyBatis都能通过其标签和属性来实现,使得动态SQL的编写既安全又高效。
653 0
|
9月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
688 0
|
11月前
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
1055 5
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1582 0
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
11月前
|
Android开发 开发者
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
本文详细介绍了如何通过自定义 `attrs.xml` 文件实现 Android 自定义 View 的属性配置。以一个包含 TextView 和 ImageView 的 DemoView 为例,讲解了如何使用自定义属性动态改变文字内容和控制图片显示隐藏。同时,通过设置布尔值和点击事件,实现了图片状态的切换功能。代码中展示了如何在构造函数中解析自定义属性,并通过方法 `setSetting0n` 和 `setbackeguang` 实现功能逻辑的优化与封装。此示例帮助开发者更好地理解自定义 View 的开发流程与 attrs.xml 的实际应用。
320 2
Android自定义View之不得不知道的文件attrs.xml(自定义属性)