(How) can I use “LIKE” in SQL queries with MyBatis safely and DB-agnostic?

后端 未结 9 920
面向向阳花
面向向阳花 2021-02-04 03:33

In MyBatis, you mark the places where parameters should be inserted into your SQL like so:

SELECT * FROM Person WHERE id = #{id}

相关标签:
9条回答
  • 2021-02-04 03:59

    The bind feature is available with mybatis version 3.2 or greater. For versions below that:- The following worked for me, in Mysql. I have used the concat function.

    <select id="getUserNamesAndEmails" parameterType="com.ashish.cardservices.models.UserCreds" resultMap="userCreds">
            select name,email from users where upper(name) like concat("%",concat(upper(#{searchQuery}),"%")) or upper(email) like concat("%",concat(upper(#{searchQuery}),"%")) and upper(email) != upper(#{email}) ;
    </select>
    
    0 讨论(0)
  • 2021-02-04 04:01

    the bind include inside the if

    <select id="select" parameterType="java.util.Map" resultType="ViajeDTO">
    
    SELECT A.ID_VIAJE ID, A.NOMBRE, A.DESCRIPCION, A.FINICIO, A.FFIN, A.LOGO, A.URL, 
            A.ID_CLIENTE IDCLIENTE, B.NOMBRE CLIENTE
    FROM VIAJE A
    INNER JOIN CLIENTE B ON (A.ID_CLIENTE = B.ID_CLIENTE)
    WHERE A.ESTATUS = 1 
    
    <if test="P_NOMBRE != null">
        <bind name="pattern" value="'%' + P_NOMBRE + '%'" />
          AND A.NOMBRE LIKE #{pattern}
    </if>
    </select>
    
    0 讨论(0)
  • 2021-02-04 04:06

    We can make use of Bind. The bind element lets you create a variable out of an expression and bind it to the context. For example:

    <select id="select" parameterType="java.util.Map" resultType="ViajeDTO">
    
        <bind name="pattern" value="'%' + P_NOMBRE + '%'" />
    
        SELECT A.ID_VIAJE ID, A.NOMBRE, A.DESCRIPCION, A.FINICIO, A.FFIN, A.LOGO, A.URL, 
                A.ID_CLIENTE IDCLIENTE, B.NOMBRE CLIENTE
        FROM VIAJE A
        INNER JOIN CLIENTE B ON (A.ID_CLIENTE = B.ID_CLIENTE)
        WHERE A.ESTATUS = 1 
    
        <if test="P_NOMBRE != null">
            AND A.NOMBRE LIKE #{pattern}
        </if>
    </select>
    

    Taking into account that the parameter to look for is P_NAME.

    0 讨论(0)
提交回复
热议问题