根据用户名称模糊查询用户信息
MyBatis全局配置文件、mysql数据库相关信息、映射文件User.xml等,都是基于这篇博客mybatis学习笔记(三):根据用户ID(主键)查询用户信息,有需要可以点击查看
使用User.xml
,添加根据用户名称模糊查询用户信息的sql语句
添加的内容如下:
<select id="findUserByName" parameterType="java.lang.String" resultType="com.xxx.qa.po.User">
SELECT * FROM USER WHERE username like '%${value}%'
select>
//根据用户名称模糊查询用户信息,得到多条记录结果
@Test
public void findUserByNameTest() throws IOException {
//mybatis配置文件
String resource = "SqlMapConfig.xml";
//得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂,传入mybatis的配置文件信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//list中的User和映射文件中resultType所指定的类型一致
List list = sqlSession.selectList("test.findUserByName", "宝宝");
System.out.println(list);
sqlSession.close();
}
......
[DEBUG]10:36:57,470,main,[Class]PooledDataSource, [Method]popConnection, Created connection 1160003871.
[DEBUG]10:36:57,471,main,[Class]JdbcTransaction, [Method]setDesiredAutoCommit, Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4524411f]
[DEBUG]10:36:57,473,main,[Class]findUserByName, [Method]debug, ==> Preparing: SELECT * FROM USER WHERE username like '%宝宝%'
[DEBUG]10:36:57,519,main,[Class]findUserByName, [Method]debug, ==> Parameters:
[DEBUG]10:36:57,558,main,[Class]findUserByName, [Method]debug, <== Total: 3
[User{id=9, username='宝宝', sex='0', birthday=Sat Jul 14 00:00:00 CST 2018, address='杭州'}, User{id=10, username='宝宝真乖', sex='1', birthday=Sat Jul 14 00:00:00 CST 2018, address='杭州萧山'}, User{id=13, username='宝宝最乖', sex='3', birthday=Sat Jul 14 00:00:00 CST 2018, address='软件园区'}]
[DEBUG]10:36:57,563,main,[Class]JdbcTransaction, [Method]resetAutoCommit, Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4524411f]
[DEBUG]10:36:57,563,main,[Class]JdbcTransaction, [Method]close, Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4524411f]
[DEBUG]10:36:57,563,main,[Class]PooledDataSource, [Method]pushConnection, Returned connection 1160003871 to pool.
......
可以看出,程序执行结果集跟数据库对应数据一致