Mybatis的XML文件SQL语句,有时需要在查询条件的参数中自定义规约,目的是在开发过程中我们可以依据字段名简单的区分入参的使用场景。
等于:原字段名
<if test="aid_id !=null and aid_id !=''">
aid_id = #{aid_id}
</if>
不等于:字段名后加_Nequal
<if test="aid_id_Nequal !=null and aid_id_Nequal !=''">
aid_id != #{aid_id_Nequal}
</if>
范围内:字段名后加_In
<if test="cdate_state_In !=null and cdate_state_In !=''">
and strpos(concat(',',#{cdate_state_In}::text,','),concat(',',cdate_state_In,','))>0;
</if>
大于:字段名后加_More
<if test="add_time_More !=null and add_time_More !=''">
and add_time > #{add_time_More}
</if>
大于等于:字段名后加_MoreEqual
<if test="add_time_MoreEqual !=null and add_time_MoreEqual !=''">
and add_time >= #{add_time_MoreEqual}
</if>
小于:字段名后加_Less
<if test="add_time_Less !=null and add_time_Less !=''">
and add_time_Less <![CDATA[ < ]]> #{add_time_Less}
</if>
小于等于:字段名后加_LessEqual
<if test="add_time_LessEqual !=null and add_time_LessEqual !=''">
and add_time_LessEqual <![CDATA[ <= ]]> #{add_time_LessEqual}
</if>
有时要在JAVA中查询日期A和日期B之间(如2020-10-01到2020-10-02 这两天内)的记录,而数据库的dateTime字段包含时分秒,为了查询到两个时间段闭区间的数据记录,
此时需要把日期B+1天,然后转换为“大于日期A且小于日期B+1”的查询条件传入Mybatis中查询。
//起始日期
String add_timeA= Comm.getString(map.get("add_timeA"));
if(!Comm.IsNullOrEmpty(add_timeA)){
map.put("add_time_MoreEqual",Comm.getDateYMDstr(add_timeA));
}
//截止日期
String add_timeB= Comm.getString(map.get("add_timeB"));
if(!Comm.IsNullOrEmpty(add_timeB)){
map.put("add_time_Less",Comm.getDateYMDaddDays(Comm.getDate(add_timeB),1));//日期B加一天
}
排序:字段名order_by
<!-- sql片段:排序 -->
<sql id="sql_orderBy">
<if test="order_by !=null and order_by !=''">
order by ${order_by}
</if>
</sql>
分页:字段名pageSize,currIndex
<!-- sql片段:分页 -->
<sql id="sql_pageSize">
<!-- pageSize=0 为不分页 -->
<if test="pageSize !=null and pageSize !=0">
limit #{pageSize} offset #{currIndex}
</if>
</sql>
动态返回字段队列:fields为需要返回的字段,多个可用逗号间隔
查询语句中默认是*全部字段,但这样查询效率较低,指定需要的字段可以提高查询效率。
<!-- sql片段:默认查询字段*,fields为字段名,多个可用逗号间隔--> <sql id="sql_fields"> <choose> <when test="fields !=null and fields !=''"> ${fields} </when> <otherwise> * </otherwise> </choose> </sql>
使用示例如下
<!-- 查询多条信息 -->
<select id="getList" resultMap="tmap" parameterType="java.util.HashMap">
SELECT <include refid="sql_fields"/>
FROM t_user_arch where 1=1
</select>
动态where条件队列:whereStr 为查询条件,每个条件语句用and开头
<!-- sql片段:动态where条件 每个条件以and开头-->
<sql id="sql_whereStr">
<if test="whereStr !=null and whereStr !=''">
${whereStr}
</if>
</sql>
可以和上面的sql_fields一起结合
使用,示例如下
<!-- 查询多条信息 -->
<select id="getList" resultMap="tmap" parameterType="java.util.HashMap">
SELECT
<include refid="sql_fields"/>
FROM t_month_cdate AS tw where 1=1
<include refid="sql_whereStr"/>
</select>