zoukankan      html  css  js  c++  java
  • Mybatis中常用sql语句

    1.变量的输入:#,$

    在xnm文件中,

    1)  通过 #{参数名} 来将参数放入sql语句中,根据数据类型输入

    例如:select * from A表 a where  a.id=#{id}

    2)   通过 ${参数名} 来表示普通字符

    例如:select * from A_${id} a where  a.id=#{id}  ,假如String id=10,

    那么等价于:select * from A_10 a where  a.id='10'

     2.条件句

    A.在执行条件条件查询时,就会用到该条语句:

      select * from A表 a where 1=1

        <if test="a.id !=null and a.id !=‘’ "> and a.id =#{id}</if>

        <if test="a.name!=null and a.name !=’’ "> and a.name =#{name}</if>

        ......

    B.在执行插入更新语句时,

      update  A表 a set

        <if test="a.id !=null and a.id !=’’ "> a.id =#{id},</if>

        <if test="a.name!=null and a.name !=’’ "> a.name =#{name},</if>

        a.age=#{age}

         ......

    C.模糊查询

      select * from A表 a where 1=1

        <if test="a.id !=null and a.id !=’’ "> and a.id =#{id}</if>

        <if test="a.name!=null and a.name !=’’ "> and a.name like concat(‘%’,#{name},‘%’)</if>

        ......

    核心思想就是:对sql语句进行拼接。同时根据需要,还可以将if条件句提取出来。然后再被引用,例如:

      <select id="xxx" parameterType="com.xxx.xxxx"  resultType="com.xxx.yyy">

        select * from A表 a where 1=1

        <include refid="yyy"><include>

      </select>

       <sql id="yyy">

        <if test="a.id !=null and a.id !=’’ "> and a.id =#{id}</if>

        <if test="a.name!=null and a.name !=’’ "> and a.name =#{name}</if>

        ......

      </sql>

    D.sql中直接使用

      SELECT IF(`status`=1,'正常','禁用') AS `status` FROM area

      Case条件语句:将值改变成其他信息输出

      SELECT `name`,CASE `status`

                WHEN 1 THEN '草稿'

                WHEN 2 THEN '提交'

                WHEN 3 THEN '审核'

                ELSE 'No' END  `status`

      FROM 表A

    3.大于小于符号

    在mybatis中是无法识别sql语句中的“>”,“<”符号的,所以应该使用 “&gt;”来代替“>”,“&lt;”来代替“<”

  • 相关阅读:
    五大常用算法之一:分治算法
    【Redis实战】双写一致性问题和解决方案
    大厂面试官喜欢这样问Redis,双写一致性、并发竞争、线程模型,我整理好了
    布隆过滤器的原理以及使用场景
    死磕 Redis- 布隆过滤器
    布隆过滤器(Bloom Filter)原理及实现
    布隆过滤器(亿级数据过滤算法)
    Java防止SQL注入2(通过filter过滤器功能进行拦截)
    java项目中如何防止sql注入
    java如入防止sql注入
  • 原文地址:https://www.cnblogs.com/momoweiduan/p/8149540.html
Copyright © 2011-2022 走看看