根据用户名称模糊查询用户信息
@Test public void findUserByNameTest() throws IOException { // 通过工厂得到SqlSession SqlSession sqlSession = null; try { // mybatis配置文件 String resource = "SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); sqlSession = sqlSessionFactory.openSession(); // 通过SqlSession操作数据库 // 第一个参数:映射文件中statement的id,等于=namespace+"."+statement的id // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数 // sqlSession.selectOne结果 是与映射文件中所匹配的resultType类型的对象 List<User> list = sqlSession .selectList("test.findUserByName", "小明"); System.out.println(list); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { // 释放资源 sqlSession.close(); } } }
User.xml
<!-- 根据用户名称模糊查询用户信息,可能返回多条 resultType:指定就是单条记录所映射的java对象 类型 ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。 使用${}拼接sql,引起 sql注入 ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value --> <select id="findUserByName" parameterType="String" resultType="ql.mybatis.pojo.User"> SELECT * FROM USER WHERE username LIKE '%${value}%' </select>
结果:
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1426420214.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@550571f6]
DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE username LIKE '%小明%'
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 3
[User [id=16, username=张小明, sex=1, birthday=null, address=河南郑州], User [id=22, username=陈小明, sex=1, birthday=null, address=河南郑州], User [id=25, username=陈小明, sex=1, birthday=null, address=河南郑州]]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@550571f6]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@550571f6]
DEBUG [main] - Returned connection 1426420214 to pool.
注意:输出的日志的sql语句不是用?占位符的,所以会引起sql注入