mybatis like 模糊查询
时间: 2023-09-13 22:08:42 浏览: 129
MyBatis provides a way to perform like or fuzzy queries using the `LIKE` operator in SQL. To implement a like query in MyBatis, you need to use the `#{}` notation to pass the search pattern as a parameter.
Here's an example of how you can perform a like query using MyBatis:
```xml
<select id="searchUsers" resultType="User">
SELECT * FROM users WHERE username LIKE #{searchTerm}
</select>
```
In this example, the `searchTerm` is the parameter that you can pass from your Java code. You can use wildcards such as `%` and `_` in the search pattern to match any characters or a single character, respectively.
To execute this query and retrieve the results, you can use the MyBatis `SqlSession` object:
```java
String searchTerm = "%john%"; // The search pattern
List<User> users = sqlSession.selectList("searchUsers", searchTerm);
```
In this code snippet, `searchUsers` is the id of the SQL query defined in the XML mapper file, and `searchTerm` is the value that will be substituted into the `LIKE` clause.
Remember to properly handle any input parameters to avoid SQL injection vulnerabilities. You can use prepared statements or other mechanisms provided by MyBatis or your database to ensure safe parameter handling.
阅读全文