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

后端 未结 9 919
面向向阳花
面向向阳花 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:47

    This will work:

    SELECT * FROM Person WHERE name LIKE '%' + #{beginningOfName} + '%';
    
    0 讨论(0)
  • 2021-02-04 03:47

    || operator worked for me in IBatis but not in Mybatis.

    In MyBatis i had to use + operator.

    SELECT *
    FROM Employee
    WHERE
    name like '%' + #{searchName,jdbcType=NVARCHAR} + '%'
    
    0 讨论(0)
  • 2021-02-04 03:49

    Typically this is done by adding the % to the parameter itself before passing it in, in whatever language you're using outside of SQL. However note that either way you might still need to do an escaping step if your search term may have _ or % in it. See eg this question for background.)

    To fix the concatenation problem in general, put MySQL into ANSI sql_mode and you get proper support for the || operator, as well as correct handling of double quotes for schema names rather than string literals.

    (If you can't do that you'd have to build a function to build the statement out of either || or CONCAT(), abstracting away the difference.)

    0 讨论(0)
  • if you're using mybatis, you can write this for s

    SELECT(" * ");
    FROM(" student ");
    WHERE(" ten LIKE '%' #{ten} '%' ");
    
    0 讨论(0)
  • 2021-02-04 03:56

    In mybatis annotation @Select

    for SQL server "... LIKE '%' + #{param} + '%' ..."

    for ORACLE "... LIKE '%' || #{param} || '%' ..."

    ref : https://mybatis.org/mybatis-3/java-api.html

    0 讨论(0)
  • 2021-02-04 03:59

    You could use bind syntax

    Quoting Official documentation

    The bind element lets you create a variable out of an OGNL expression and bind it to the context. For example:

    <select id="selectBlogsLike" resultType="Blog">
      <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
      SELECT * FROM BLOG
      WHERE title LIKE #{pattern}
    </select>
    
    0 讨论(0)
提交回复
热议问题