zoukankan      html  css  js  c++  java
  • 10-动态SQL语句

    一、 -if

    当你要查询的参数不确定时:参数可能只有username或者password或者有多个甚至什么都没有

    test 类

        @Test
        public void testFindByCondition(){
            User u=new User();
            u.setUsername("醉人");
            List<User> users=userMapping.findUserByCondition(u);
            for (User user:users){
                System.out.println(user);
            }
        }
    

    mapping.xml(大小写、名称一致很重要)

        <!--根据条件查询-->
        <select id="findUserByCondition" resultType="domain.User">
            select *from user where 1=1
            /*username应该与实体表中的名字一致,包括大小写*/
            <if test="username!=null">
            /*#{username} 应该与实体表中的名字一致,包括大小写*/
                and username=#{username}
            </if>
            <if test="id!=null">
                and id =#{id}
            </if>
        </select>
    

    二、 -where

        <select id="findUserByCondition" resultType="domain.User">
            select *from user
            <where>
                <if test="username!=null">
                    and username=#{username}
                </if>
                <if test="id!=null">
                    and id=#{id}
                </if>
            </where>
        </select>
    

    用 where 的话比只有 if 的 sql 语句更简洁

    三、 -foreach

    select *from user where id in(1,2)

        <select id="findUserInIds" resultType="domain.User">
            select *from user
            <where>
                <if test="list !=null and list.size()>0">
                    <foreach collection="list" item="item" open="and id in(" close=")" separator=",">
                        #{item}
                    </foreach>
                </if>
            </where>
        </select>
    
        @Test
        public void testFindUserInIds(){
            ArrayList<Integer> list=new ArrayList<Integer>();
            list.add(1);
            list.add(2);
    
            List<User> users=userMapping.findUserInIds(list);
            for (User user:users){
                System.out.println(user);
            }
        }
    

    扩展:sql语句很多重复怎么办?

        <sql id="defaultUser">
            select *from user
        </sql>
    

    调用

    注意:如果后面还要添加语句,上面的 sql 语句后面不要添加分号

        <select id="findAll" resultType="domain.User">
            <include refid="defaultUser"/>
            /*select *from user;*/
        </select>
    
  • 相关阅读:
    使用图形化界面打包自己的类库
    搭建自己的NuGet服务器,上传自定义NuGet包
    在内部架设NuGet服务器
    Prism简介
    Nhibernate Icreteria 分页查询
    uDig介绍
    基于Geoserver配置多图层地图以及利用uDig来进行样式配置
    如何在GeoServer上发布一张地图
    XML的SelectNodes使用方法以及XPath
    coded ui run in interactive mode
  • 原文地址:https://www.cnblogs.com/zuiren/p/11406127.html
Copyright © 2011-2022 走看看