本文主要针对MySQL
----------------------------------------------------------------------------------------------------------
用generatorConfig.xml工具生成我有总结过:http://www.cnblogs.com/fengchaoLove/p/5790352.html
了解的可以去看看。
本文主要针对纯手写。
-----------------------------------------------------------------------------------------------------------
mapper.xml-->dao接口-->service-->Controller
Entity实体类
增删改查,我们先说查select
select *(要查询的字段)from 表名 where id='',and ...
mapper.xml;
1 xml version="1.0" encoding="UTF-8" ?> 2 DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 4 <mapper namespace="com.hebg3.mobiledealer.modules.client.sales.dao.CustomerDao"> 5 6 <select id="get" resultType="TCustomer" paramType="string"> 7 SELECT 8 * 9 FROM t_customer a 10 WHERE a.id = #{id}
但在工作中,我们发现其实我们要查的没有那么简单,和我学习时候的几点出入:
1.实体类要用驼峰命名,而数据库中的字段是下划线割开,导致unknown错误。
2.我们往往不是通过一个字段来查询,是好几个字段,甚至还有动态查询(有这个字段就查,没有就忽略)。
3.条件查询中有List,需要循环查找
4.条件中有关模糊查询。
先来解决第一个问题:
1 2 <mapper namespace="com.hebg3.mobiledealer.modules.client.store.order.dao.OrderDao"> 3 4 <sql id="tOrderColumns"> 5 a.id AS "id", 6 a.order_no AS "orderNo", 7 a.t_customer_id AS "customer.id", 8 a.sys_office_id AS "companyOffice.id", 9 a.order_date AS "orderDate", 10 a.document_status AS "documentStatus", 11 a.send_date AS "sendDate", 12 a.open_id AS "openId", 13 a.create_by AS "createBy.id", 14 a.create_date AS "createDate", 15 a.update_by AS "updateBy.id", 16 a.update_date AS "updateDate", 17 a.remarks AS "remarks", 18 a.del_flag AS "delFlag", 19 20 sql> 21 22 23 24 <select id="findPageOrder" resultType="TOrder"> 25 SELECT 26 27 <include refid="tOrderColumns" /> 28 FROM t_order a 29 <include refid="tOrderJoins" /> 30 <where> 31 32 <if test="Id!=null and id!=''"> 33 id=#{Id} 34 if> 35 36 37 select>
如果想再加入一个查询条件;
在if标签 下面加入
1 <if test="documentStatus!=null and documentStatus!=''"> 2 AND a.document_status =#{documentStatus} 3 if>
如果查询条件中有List集合,可以在参数类中加入List类型的属性,比如是List
1 <if test="documentStatusList != null"> 2 AND a.document_status in 3 4 <foreach item="item" index="index" collection="documentStatusList" open="(" separator="," close=")"> 5 #{item} 6 foreach> 7 8 if>
当然如果你想排序的话
1 <choose> 2 <when test="page !=null and page.orderBy != null and page.orderBy != ''"> 3 ORDER BY ${page.orderBy} 4 when> 5 <otherwise> 6 ORDER BY a.create_date DESC 7 otherwise> 8 choose>
几个注意的细节例如
这其中customer都是实体类。
希望对大家有所帮助。。