简体   繁体   中英

mybatis mapper search across multiple columns using same param

Mapper:

List<Person> list(@Param("search") String search);

SQL in mapper XML:

<select id="searchPersons" resultType="Person">
select * from persons
where firstname like '%#{search}%' or lastname like '%#{search}%'
</select>

Here, I am trying to search on firstname and lastname columns with only parameter from the mapper class. However, I am getting the exception below:

Caused by: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086) ~[mysql-connector-java-5.1.29.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989) ~[mysql-connector-java-5.1.29.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975) ~[mysql-connector-java-5.1.29.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920) ~[mysql-connector-java-5.1.29.jar:na]
    at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3796) ~[mysql-connector-java-5.1.29.jar:na]
    at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3778) ~[mysql-connector-java-5.1.29.jar:na]
    at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4599) ~[mysql-connector-java-5.1.29.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_80]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_80]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_80]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_80]
    at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:63) ~[mybatis-3.2.5.jar:3.2.5]

you must use ${param_name} instead of #{param_name}. MyBatis insert ${} params in the sql string before compile the Statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM