During project development, when doing Mybatis dynamic query, I encountered a problem: when MySQL is conducting LIKE fuzzy query, the results can be retrieved normally by entering English, but the results obtained by entering Chinese are empty.
Since it is requested using GET, in order to ensure that Chinese is not garbled, the Chinese language is encoded once after the console receives the request parameters.
try {realName = new String(realName.getBytes("GBK"), "UTF-8");} catch (UnsupportedEncodingException exception) {logger.error("realName error occurred while performing UTF-8 encoding," + exception.toString());}Mybatis dynamic SQL mapping, the specific SQL is as follows:
First, use fuzzy query to retrieve English. Start the project, enter the English "test", and the results obtained by searching according to the English content are as follows:
We can see that SQL is executed normally. Using "test" to retrieve 2 results, the contents of the corresponding fields in the database are Zhang San test02 and Zhang San test. Normally, if we enter the Chinese "Zhang", we can also query these two data. Let's try using fuzzy query to retrieve Chinese. Start the project, enter the Chinese "Zhang", and the search results are as follows:
We can see that the result retrieved here is 0 records, and the Chinese content of the conditions is not garbled, which is different from the expected one. Copying the same SQL statement into SQLyog can result in normal results.
There was no such problem when using SQLServer. This happened this time using MySQL. It is suspected that the contents of SQLServer and MySQL configurations were different when Mybatis configured the data source environment. After careful comparison and online review of relevant content, I found that when MySQL searches Chinese, I need to add the parameter useUnicode=true&characterEncoding=UTF-8 after jdbcURL to specify the encoding format.
Complete URL:
jdbc:mysql://127.0.0.1:3306/fanyl_web?useUnicode=true&characterEncoding=UTF-8
After modifying MySQL's jdbcURL, start the project and continue to enter the Chinese "Zhang". The search results are as follows:
A total of 3 results were retrieved. At this point, the problem that Mybatis cannot search for Chinese when using MySQL to perform fuzzy query was solved.
In addition, several common parameter descriptions in MySQL's jdbcURL:
The above is what I introduced to you. What should I do if I can’t search results when using Mybatis to use MySQL fuzzy query? I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!