zoukankan      html  css  js  c++  java
  • 动态SQL 与sql片段 foreach

    目的是为了减少代码量   方便

    <!-- 动态sql -->
    <select id="findUserLists" parameterType="entity.UserQueryVo" resultType="entity.UserCoustom">
    select * from userss

    <where>
    <if test="userCoustom!=null">
    <if test="userCoustom.sex!=null and userCoustom.sex!=''">
    And sex=#{userCoustom.sex}
    </if>
    <if test="userCoustom.username!=null and userCoustom.username!=''">
    And username=#{userCoustom.username}
    </if>

    </if>
    </where>
    </select>

    <select id="findUserListLike" parameterType="entity.UserQueryVo" resultType="entity.UserCoustom">
    select * from userss

    <where>
    <include refid="query_user_where"></include>
    </where>
    </select>

    <!-- sql片段 作用是将sql语句中大量使用的部分截取出来 减少代码量
    类似于JAVA中的方法封装
    -->
    <sql id="query_user_where">
    <if test="userCoustom!=null">
    <if test="userCoustom.sex!=null and userCoustom.sex!=''">
    And sex=#{userCoustom.sex}
    </if>
    <if test="userCoustom.username!=null and userCoustom.username!=''">
    And username like '%${userCoustom.username}%'
    </if>

    </if>
    </sql>

    <!-- foreach 当选取多个数据的时候使用 比如批量删除等 -->

    <select id="findUserForeach" parameterType="entity.UserQueryVo"
    resultType="entity.UserCoustom">
    Select * From userss Where 1=1
    <if test="ids!=null">

    <!--
    collection 对象中集合的属性名
    item 每个遍历生成的对象
    open开始遍历时拼接的字符串
    close结束遍历时拼接的字符串
    separator 连接时使用 例如or或者,
    -->


    <foreach collection="ids" item="user_id" open="and (" close=")" separator="or">

    如果sql语句是select * from userss where id in(id1,id2,id3);  则将上面的属性修改一下

    <foreach collection="ids" item="user_id" open="and id in (" close=")" separator=",">

    id=#{user_id}
    </foreach>
    </if>
    </select>

  • 相关阅读:
    使用MyEclipse可视化开发Hibernate实例
    Query查询
    Java Filter过滤机制详解(转载)
    持久化对象的状态转换
    经典SQL语句大全
    持久对象的生命周期
    Mysql命令操作
    hibernate常用的接口和类的方法以及持久化对象的状态变化
    mysql的安装
    Visual C# 2008+SQL Server 2005 数据库与网络开发 10.8 小结
  • 原文地址:https://www.cnblogs.com/cpx123/p/7652568.html
Copyright © 2011-2022 走看看