Mybatis模糊查询CONCAT函数、bind标签

  • Post author:
  • Post category:其他




利用MySQL的CONCAT函数,这种方式对数据库有要求

	<select id="findByUsername" resultType="String">
        select username from user
        <where>
            <if test="username != null and username != ''">
                AND username LIKE CONCAT('%',#{username},'%')
            </if>
        </where>
    </select>



代码层面加%号,性能相对会高一点,毕竟没有用函数,与数据库无关

	//UserServiceImpl
	return userMapper.findByUsername("%" + username + "%");
<select id="findByUsername" resultType="String">
        select username from user
        <where>
            <if test="username != null and username != ''">
                AND username LIKE #{username}
            </if>
        </where>
    </select>



bind标签,性能相对会高一点,毕竟没有用函数,与数据库无关

	<select id="findByUsername" resultType="String">
        select username from user
        <where>
            <if test="username != null and username != ''">
            	<bind name="name" value="'%'+username+'%'"/>
                AND username LIKE #{name}
            </if>
        </where>
    </select>



总结

第一种写法很多人推荐,但最好的还是后两种方法,因为没有使用数据库函数,处理都是在业务层做好了的,数据库处理时性能相对会更高一些,尤其是数据量大的时候尤其明显。



版权声明:本文为weixin_43933728原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。