MyBatis模糊查询不报错但查不出数据的一种解决方案

今天在用MyBatis写一个模糊查询的时候,程序没有报错,但查不出来数据,随即做了一个测试,部分代码如下:

[html]  view plain  copy
 
  1. @Test  
  2. public void findByNameTest() throws IOException {  
  3.     String resource = "SqlMapConfig.xml";  
  4.     InputStream inputStream = Resources.getResourceAsStream(resource);  
  5.     SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()  
  6.             .build(inputStream);  
  7.     SqlSession sqlSession = sqlSessionFactory.openSession();  
  8.     List<Userlist = sqlSession.selectList("test.findByName", "远");  
  9.     System.out.println(list);  
  10.     sqlSession.close();  
  11.   
  12. }  


User.xml映射文件

[html]  view plain  copy
 
  1. <select id="findByName" parameterType="java.lang.String" resultType="pojo.User">  
  2.     SELECT * FROM USER WHERE username LIKE '%${value}%'  
  3. </select>  

结果日志显示

[plain]  view plain  copy
 
  1. Opening JDBC Connection  
  2. Created connection 2040926578.  
  3. Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@79a61172]  
  4. ==>  Preparing: SELECT * FROM USER WHERE username LIKE '%远%'   
  5. ==> Parameters:   
  6. <==      Total: 0  
  7. []  
  8. Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@79a61172]  
  9. Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@79a61172]  
  10. Returned connection 2040926578 to pool.  

查询出的结果数量为0

解决方法:

 在SqlMapConfig.xml配置文件中把

[html]  view plain  copy
 
  1. <property name="url" value="jdbc:mysql://localhost:3306/mybatistest" />  

改为:

[html]  view plain  copy
 
  1. <property name="url" value="jdbc:mysql://localhost:3306/mybatistest?characterEncoding=utf8" />  

指定一个字符的编码格式,问题解决。

猜你喜欢

转载自www.cnblogs.com/mabingxue/p/9156955.html
今日推荐