映射器:
List<Person> list(@Param("search") String search);
映射器XML中的SQL:
<select id="searchPersons" resultType="Person">
select * from persons
where firstname like '%#{search}%' or lastname like '%#{search}%'
</select>
在这里,我尝试使用mapper类中的参数搜索firstname
和lastname
列。但是,我得到以下例外:
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]
答案 0 :(得分:1)
您必须使用$ {param_name}而不是#{param_name}。在编译Statement之前,MyBatis在sql字符串中插入$ {} params。