MyBatis模糊查詢不報錯但查不出資料的一種解決方案
阿新 • • 發佈:2019-01-09
今天在用MyBatis寫一個模糊查詢的時候,程式沒有報錯,但查不出來資料,隨即做了一個測試,部分程式碼如下:
@Test public void findByNameTest() throws IOException { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> list = sqlSession.selectList("test.findByName", "遠"); System.out.println(list); sqlSession.close(); }
User.xml對映檔案
<select id="findByName" parameterType="java.lang.String" resultType="pojo.User">
SELECT * FROM USER WHERE username LIKE '%${value}%'
</select>
結果日誌顯示
Opening JDBC Connection
Created connection 2040926578.
Setting autocommit to false on JDBC Connection [[email protected] ]
==> Preparing: SELECT * FROM USER WHERE username LIKE '%遠%'
==> Parameters:
<== Total: 0
[]
Resetting autocommit to true on JDBC Connection [[email protected]]
Closing JDBC Connection [[email protected]]
Returned connection 2040926578 to pool.
查詢出的結果數量為0
解決方法:
在SqlMapConfig.xml配置檔案中把
<property name="url" value="jdbc:mysql://localhost:3306/mybatistest" />
改為:
<property name="url" value="jdbc:mysql://localhost:3306/mybatistest?characterEncoding=utf8" />
指定一個字元的編碼格式,問題解決。