Mybatis中sql的相关优化以及个人心得

1.模糊匹配时候不要用

like "%@${item}@%"   模糊匹配时候因为不能用“#”,因为带单引号的原因
解决:使用concat代替 like concat('%@',#{item},'@%')

此方式可以防止$带来的sql注入问题

2.关于级联

<resultMap type="com.xxx.Image" id="Image">
	<result column="id" jdbcType="VARCHAR" property="id" />
	<association property="aaa" javaType="com.xxxxxx.aaa">
		<result column="aaaId" jdbcType="BIGINT" property="id" />
	</association>
</resultMap>

数据库中包含两个相同字段的情况 A表B表相关联,主键均为id,则可以为其换别名 column=“id”,column="aaaId"防止冲突

3.关于时间类型的字段
数据库中某字段为datetime类型,若要取某时间段内的数据,可以转换为时间戳

<if test="startTime != null and startTime !='' ">
	and unix_timestamp(s.created)*1000 &gt;= #{startTime}
</if>
<if test="endTime != null and endTime !='' ">
	and unix_timestamp(s.created)*1000 &lt;= #{endTime}
</if>

上面的sql则为取对应时间内的数据
unix_timestamp为将datetime字段转换为时间戳(单位为秒)
这样方便比较,写起来也简便

4.分享一个查询相似图片的sql

select
	*
	from
	image s
	<choose>
	
		<when test="color == null">
		 where 1=1
		</when>
		
		<otherwise>
		,
		(
		select
		t.id,
		truncate
		  (
			sqrt
			  (
				2*power((t.red  - #{color.red}), 2) + 4*power((t.green - #{color.green}), 2) + 3*power((t.blue - #{color.blue}), 2)
			  ),2
		  ) as num
		from
		image t
		)
		as t2
		where
		s.id = t2.id
		and
		t2.num &lt; #{color.threshold}
		</otherwise>
		
	</choose>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值