今天在用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 [com.mysql.jdbc.JDBC4Connection@79a61172]
- ==> Preparing: SELECT * FROM USER WHERE username LIKE '%远%'
- ==> Parameters:
- <== Total: 0
- []
- Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@79a61172]
- Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@79a61172]
- 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" />
指定一个字符的编码格式,问题解决。