业务场景:对于某个数据库,在新增或者修改数据之前,需要校验某个有唯一索引的字段内容是否已经存在,如果存在,查询出已存在的数据绑定的信息并返回(抛错或者return Result.error)
1、如果需要查询信息并且返回:
单独写一个select,查询已经有的信息并且返回:
Mapper.xml
<select id="getInfosByRfid" resultType="返回DO实体类">
SELECT rfid, info1 , info2....
from xxxinfo
and rfid in
<foreach item="rfid" index="index" collection="rfids" open="(" separator="," close=")">
#{rfid}
</foreach>
</select>
如果查询到了结果,返回你想要的数据集合,如果查询不到,结果列表是空
2、如果不需要信息,只需要是否重复(效率优化):
<select id="checkReapeatByRfid" parameterType="string" resultType="integer">
select exists (select * from xxxinfo where rfid in
<foreach item="item" index="index" collection="rfidList" open="(" separator="," close=")">
#{item}
</foreach>
) as exist_result
</select>
如果查询到了结果,返回1,反之,返回0;
返回的字段越少,效率越高,内存占用越小。
唯一索引可能存在的坑:使用逻辑删除时,唯一索引依然存在,虽然记录已经逻辑删除,但是需要校验的字段内容仍然被占用,导致无法更新或新增。
这个目前还没写, 等下一篇文的时候再搞吧。