mybatis中mapper.xmlSQL手写总结

工作流成简述:
mapper.xml–>dao接口–>service–>Controller

查询:
  select * from 表名 where …
  mapper.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">
<!--客户映射 指定到dao接口 -->
<mapper namespace="com.hebg3.mobiledealer.modules.client.sales.dao.CustomerDao">
<!--id与dao接口的方法名一直,指定结果类型,和参数类型 -->
<select id="get" resultType="TCustomer" paramType="string">
        SELECT 
            *
        FROM tablename a
        WHERE a.id = #{id}<!--主键  -->

但是工作中我们会遇到一下情况:
    1.实体类要用驼峰命名,而数据库中的字段是下划线割开,导致unknown错误。
    2.我们往往不是通过一个字段来查询,是好几个字段,甚至还有动态查询(有这个字段就查,没有就忽略)。
    3.条件查询中有List,需要循环查找
    4.条件中有关模糊查询。

先看第一种:

<!-- 库存映射 -->
<mapper namespace="com.hebg3.mobiledealer.modules.client.store.order.dao.OrderDao">

    <sql id="tOrderColumns">
        a.id AS "id",<!-- 主键 -->
        a.order_no AS "orderNo",<!-- 订单编号 -->
        a.t_customer_id AS "customer.id",<!-- 客户编号 -->
        a.sys_office_id AS "companyOffice.id",<!-- 公司编号 -->
        a.order_date AS "orderDate",<!-- 订单日期 -->
        a.document_status AS "documentStatus",<!-- 订单状态 -->
        a.send_date AS "sendDate",<!-- 发送时间 -->
        a.open_id AS "openId",<!-- 微信编号 -->
        a.create_by AS "createBy.id",<!-- 建立人 -->
        a.create_date AS "createDate",<!-- 建立时间 -->
        a.update_by AS "updateBy.id",<!-- 更新人 -->
        a.update_date AS "updateDate",<!-- 更新时间 -->
        a.remarks AS "remarks",<!-- 备注 -->
        a.del_flag AS "delFlag",<!-- 删除标志 -->
        
    </sql>

    
<!-- 根据条件取得 订单信息列表 -->
    <select id="findPageOrder" resultType="TOrder">
        SELECT
<!-- refid属性与上面spl标签的Id一致 -->
	<include refid="tOrderColumns" />
        
        FROM t_order a
        
        <include refid="tOrderJoins" />
        
        <where>
            
            <if test="Id!=null and id!=''">
                id=#{Id}
            </if>
            
    </select>

标签实现动态查询。
  如果想再加入一个查询条件;
  在if标签 下面加入

1 <if test="documentStatus!=null and documentStatus!=''">
2                 AND a.document_status =#{documentStatus}
3             </if>

如果查询条件中有List集合,可以在参数类中加入List类型的属性,比如是List documentStatusList:并生成get,set方法;

<if test="documentStatusList != null"><!-- 根据单据状态查找 -->
                AND a.document_status in
<!-- foreach标签需要指定四个属性,item,index下标,collection要与指定的属性名一直,open指定断开符号和结束符号 -->
                <foreach item="item" index="index" collection="documentStatusList" open="(" separator="," close=")">
                    #{item}
                </foreach>
                 
            </if>

当然如果你想排序的话

<choose>
            <when test="page !=null and page.orderBy != null and page.orderBy != ''"><!-- 根据 排序字段 排序 -->
                ORDER BY ${page.orderBy}
            </when>
            <otherwise>
                ORDER BY a.create_date DESC
            </otherwise>
        </choose>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yanwendonge/article/details/88991329