Mybatis where 1 = 1 and Tags

When splicing query statements in mybatis, it occasionally appears that there may be no value of a field after where, which leads to all conditions being invalid and makes where meaningless. However, it is also possible that these conditions may exist. The most common way to solve this problem is to:

Add 1 = 1 after where

<select id="findActiveBlogLike" resultType="Blog"&>
 WHERE 1=1
 <if test="state != null"&>
 and state = #{state}

But this method has one of the biggest disadvantages, which is that it leads to the invalidation of the index on the data table, if there is an index. And it’s a rubbish condition

The where element knows to insert a “where” clause only if more than one if condition has a value. Moreover, if the final content starts with “and” or “, the where element also knows how to remove them.

If the where element doesn’t play according to the normal routine, we can still customize the function we want by customizing the trim element. For example, a custom trim element equivalent to the where element is:


Similar Posts: