首页 技术 正文
技术 2022年11月17日
0 收藏 899 点赞 3,058 浏览 1889 个字

刚来到一家新公司, 翻看项目代码, 发现一位同事写的查询逻辑很好, 不用插件, 一个语句完成了分页条件查询.

而我之前一般都是在业务层对参数进行判断, 如果有条件,就调用条件查询的方法, 如果没有条件, 就调用查询所有的方法, 代码冗余较多

贴下代码:

1, 首先定义resultMap:

  

<resultMap id="xxxModel" type="com.aaa.XxxModel">
<id column="id" javaType="java.lang.Long" jdbcType="BIGINT" property="id" />
<result column="ip" javaType="java.lang.String" jdbcType="VARCHAR" property="ip" />
<result column="port" javaType="java.lang.Integer" jdbcType="INTEGER" property="port" />
<result column="userName" javaType="java.lang.String" jdbcType="VARCHAR" property="userName" />
<result column="password" javaType="java.lang.String" jdbcType="VARCHAR" property="password" />
<result column="lineNum" javaType="java.lang.Integer" jdbcType="INTEGER" property="lineNum" />
<result column="isInternation" javaType="java.lang.Integer" jdbcType="INTEGER" property="isInternation" />
<result column="createDate" javaType="java.lang.String" jdbcType="VARCHAR" property="createDate" />
<result column="updateDate" javaType="java.lang.String" jdbcType="VARCHAR" property="updateDate" />
</resultMap>2, 定义sql片段, 方便阅读:
//条件和分页参数的封装, 利用动态sql, 特别是模糊查询的%拼接, 很赞:
<sql id="pageListCount">
from anti_http_proxy a
<if test="groupId != null and groupId !=''">
LEFT JOIN anti_proxy_group b on a.`host` = b.`host`
LEFT JOIN anti_group_server c on b.group_id = c.group_id
</if>
where 1=1
<if test="ip != null and ip !=''">
and a.`host` like CONCAT('%','${ip}','%')
</if>
<if test="groupId != null and groupId !=''">
and c.id = #{groupId}
</if>
ORDER BY a.gmt_modified desc
<if test="(pageNumber != null and pageNumber != '' or pageNumber == 0) and pageSize != null and pageSize != ''">
limit #{pageNumber}, #{pageSize}
</if>
</sql><sql id="resultCol">
a.id
,a.`host` as ip
,a.`port`
,a.username as userName
,a.`password`
,a.band as lineNum
,a.international as isInternation
,DATE_FORMAT(a.gmt_create,'%Y-%m-%d %H:%i:%s') as createDate
,DATE_FORMAT(a.gmt_modified,'%Y-%m-%d %H:%i:%s') as updateDate
</sql>
3, 完成查询方法
<select id="selectAllByPage" resultMap="xxxModel">
select
<include refid="resultCol" />
<include refid="pageListCount" />
</select>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,135
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,603
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,447
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,221
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,855
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,941