zoukankan      html  css  js  c++  java
  • 02

    动态SQL

    什么是?

    系统运行过程中,动态生成的SQL语句

    为什么?

    当我们不能确定用户操作,所要使用的具体SQL的时候.

    案例: 搜索笔记功能 按用户名 笔记本名 笔记名 搜索

       搜索功能    按用户 A  B  C 
    
       select * from cn_note where userName=#{} and bookName=#{} and noteTitle=#{}
    

    如何实现?

    • {id}

    if标签

    if起到选择判断的作用

    语法:

    应用:

        <select id="findNotes" parameterType="Map">
        select * from cn_note
        where cn_note_status_id="1"
        <if test="userName!=null"> 
                and cn_user_name=#{userName}</if>
        <if test="bookName!=null">
                and cn_notebook_name=#{bookName}</if>
       <if test="noteName!=null">
            and cn_note_name=#{noteName}</if>
        </select>
    

    相当于JAVA中的switch语句,当匹配(when)到符合条件的语句后,直接输入,结束匹配;

    当没有匹配到任何条件,最后输出otherWise

    语法:

        <choose>
            <when test=""></when>
            <when test=""></when>
            <when test=""></when>
            <otherwise></otherwise>
        </choose>
    

    where/set

    在开始标签的位置自动输入 where关键字.

    在拼凑SQL语句的过程中,会自动处理多余的and/or/空格.

    语法:

        <where>
            <if test=""></if>
            <if test=""></if>
        </where>
    
        <set>
            <if test=""></if>
            <if test=""></if>
        </set>
    

    trim

    语法:

        <trim prefix="where"  prefixOverrides="and/or"></trim>
    

    练习:批量删除笔记

        delete from cn_note where cn_note_id 
        in (#{id1},#{id2},#{id3}.....)
        <foreach collection="list/array"
                    item="id"
                    open="("
                    close=")"
                    separator=",">
        #{id}
        </foreach>
    

    组合查询笔记的功能

    标题 状态 开始时间 结束时间 搜索按钮

    搜索列表

    标题 状态 创建时间

    发送Ajax请求

    • 绑定事件:搜索按钮的单击事件

    • 获取参数:标题 状态 开始时间 结束时间

    • 请求地址:/note/manage.do

    服务器处理

    • Controller.find(String userId,String title,String

    status,Stringbegin,String end)

    • Service.find(String userId,String title,String status,

    String begin,String end)

    • NoteDao.findNotes(Map params)

    • Mapper select * from cn_note 动态SQL

    Ajax回调处理

    • success

    遍历返回的数据集合,显示在结果列表中

    • error

    提示:搜索失败

    作业:重构搜索笔记需求的mapper定义

    • 使用

    • 使用

  • 相关阅读:
    MongoDB 分片机制
    MongoDb的“not master and slaveok=false”错误及解决方法
    MongoDB 副本集复制配置
    spring,mybatis整合配置文件
    Tomcat-正统的类加载器架构
    CSS3系列三(与背景边框相关样式 、变形处理、动画效果)
    如果您想省略JS里的分号,了解一下JS的分号插入原理吧
    CSS3系列二(媒体支持、文字与字体相关样式、盒相关样式)
    CSS3系列一(概述、选择器、使用选择器插入内容)
    HTML5系列四(WebWorker、地理定位)
  • 原文地址:https://www.cnblogs.com/tangshengwei/p/6618426.html
Copyright © 2011-2022 走看看