1 在实际应用中,无论是企业级项目还是互联网项目,使用得最多的肯定是查询操作,不管是在列表中展示所有数据的操作,还是对单个数据的修改或是删除操作,都需要事先查询并展示相应的数据。
2 查询操作通常可以分为按条件查询和查询所有
2.1 在真实的项目中,默认是这样进行,有条件时,一定就是条件查询,条件为空【注意,这不是无条件】时,就查询所有的。
2.2 对于查询的结果,无法估计和预知,数据库中的数据量可能很多,如果让查出来的数据在一个页面中全部显示出来,势必会造成页面数据的可读性和显示性能变差,因此一般都需要考虑将查询的结果进行分页处理,即分页显示。
3 查询的真实实现
3.1 按条件【多条件】查询
3.2 分页查询
4 查询实现的技术—PO类的实现
4.1创建持久化类,与库表对应的类
4.2创建持久化类,与业务需要的数据对应的类
4.3创建持久化类,与当前页面显示对应的类【包括表列,分页信息,查询条件】
5 创建查询接口
在写接口方法时,一定要首先明确
- 方法名
- 入参是什么
- 返回的是什么【列单,单行信息,单值信息???】
- 返回的数据的业务解释是什么【用户,用户数,用户列表???】
使用mybatis实现接口时,写对应的mapper.xml文件时,一定要理清楚对应的方法名和方法入参,返回值
建议把查询条件单独写一个SQL片段
建议把分页单独写一个SQL片段
然后
示例:
<!--SQL片段-CustomerList查询条件 -->
<sql id="selectCustomerListWhere">
<where>
<if test="cust_name != null" >
cust_name like "%"#{cust_name}"%"
</if>
<if test="cust_source != null" >
and cust_source = #{cust_source}
</if>
<if test="cust_industry != null" >
and cust_industry = #{cust_industry}
</if>
<if test="cust_level != null" >
and cust_level = #{cust_level}
</if>
</where>
</sql>
limit #{start},#{rows}
<!-- 查询客户列表 -->
<select id="selectCustomerList" **parameterType="customer"** **resultType="customer"**>
SELECT
cust_id,
cust_name,
cust_user_id,
cust_create_id,
b.dict_item_name cust_source,
c.dict_item_name cust_industry,
d.dict_item_name cust_level,
cust_linkman,
cust_phone,
cust_mobile,
cust_createtime
FROM
customer a
LEFT JOIN (
SELECT
dict_id,
dict_item_name
FROM
base_dict
WHERE
dict_type_code = '002'
) b ON a.cust_source = b.dict_id
LEFT JOIN (
SELECT
dict_id,
dict_item_name
FROM
base_dict
WHERE
dict_type_code = '001'
) c ON a.cust_industry = c.dict_id
LEFT JOIN (
SELECT
dict_id,
dict_item_name
FROM
base_dict
WHERE
dict_type_code = '006'
) d ON a.cust_level = d.dict_id
**<include refid="selectCustomerListWhere"/>**
**<!-- 执行分页查询 -->
<if test="start !=null and rows != null">
limit #{start},#{rows}
</if>**
</select>
本文探讨了在企业级和互联网项目中常见的数据库查询操作,包括条件查询和分页查询的实现方法。通过使用MyBatis框架,文章详细介绍了如何创建持久化类,设计查询接口,并利用SQL片段进行条件筛选和分页处理,以提高查询效率和用户体验。

被折叠的 条评论
为什么被折叠?



