zoukankan      html  css  js  c++  java
  • mapper.xml中动态sql抽取重复项

    mabatis重点是通过标签对sql灵活的组织,通过配置的方式完成输入 输出映射.

    1.对mapper.xml中重复的sql抽取统一维护,以及foreach使用

    UserMapperCustom.xml

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.itcast.mybatis.mapper.UserMapperCustom"> <!-- 定义一个sql片段,将重复的sql语句抽取出来 建议:定义查询条件以单表为单位去定义,sql片段可重用性才高 建议不要包括where 建议以单个为单位去定义查询条件,一般要将查询条件写全 --> <sql id="query_user_where"> <!-- 如果有条件值再拼接 --> <if test="user!=null"> <if test="user.username!=null and user.username!=''"> <!-- 用户输入条件值再拼接 --> and username like '%${user.username}%' </if> <if test="user.sex!=null and user.sex!=''"> and sex = #{user.sex} </if> <!-- 下边要拼接: AND id IN (1,10,16) --> <!-- 遍历id列表 collection:接收输入参数中的集合属性 item:每次循环定义一个对象名 open:开始循环时拼接的sql close:结束循环时拼接的sql separator:每两次循环中间拼接的sql --> <foreach collection="ids" item="id" open=" AND id IN ( " close=" ) " separator=","> #{id} </foreach> <!-- 思考:如何拼接 AND (id=1 OR id=10 OR id=16) 实现 SELECT * FROM USER WHERE sex = '1' AND  id IN (1,10,16)
    -->
                </if>
        </sql>
    
        <!-- 综合条件查询用户 -->
        <select id="findUserList" parameterType="queryUserVo"
            resultType="user">
            select id,username,birthday,sex,address from user
        
           <!-- where标签 相关于where关键字,可以将条件中的第一个and去掉 -->
            <where>
            <!-- 引用sql片段
            如果跨mapper引用需要前边加namespace
             -->
            <include refid="query_user_where"></include>
           </where>
        </select>
        
        <!-- 综合条件查询用户记录汇总 -->
        <select id="findUserCount" parameterType="queryUserVo" resultType="int">
            select count(*) from user
             <!-- where标签 相关于where关键字,可以将条件中的第一个and去掉 -->
            <where>
            <!-- 引用sql片段
            如果跨mapper引用需要前边加namespace
             -->    
            <include refid="query_user_where"></include>
           </where>
        </select>
    
    </mapper>
    
    
    UserMapperCustom.java
    public interface UserMapperCustom {
        
        //综合条件查询用户信息
        public List<User> findUserList(QueryUserVo queryUserVo) throws Exception;
        
        //综合条件查询用户记录总数
        public int findUserCount(QueryUserVo queryUserVo) throws Exception;
    
    }
  • 相关阅读:
    MongoDB数据导入hbase + 代码
    Hbase批量插入优化记录
    net.sf.fjep.fatjar_0.0.32 eclipse4.x 可以用的jar包
    %E3%80%90%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E3%80%91
    学习《深度学习入门:基于Python的理论与实现》高清中文版PDF+源代码
    《Python生物信息学数据管理》中文PDF+英文PDF+代码
    推荐《R数据可视化手册》高清英文版PDF+中文版PDF+源代码
    学习优化《机器学习与优化》中文PDF+英文PDF
    入门python:《Python编程从入门到实践》中文PDF+英文PDF+代码学习
    推荐《SQL基础教程(第2版)》中文PDF+源代码+习题答案
  • 原文地址:https://www.cnblogs.com/wwwzzz/p/8277241.html
Copyright © 2011-2022 走看看