Mybatis映射文件SQL语句模糊查询
1. “%”#{value}"%" 在参数中不需要添加 %_ 推荐使用
2. ‘%${value}%’ 在参数中不需要添加 %_
3. #{abc} 在参数中添加 %_
#和$的区别和注意事项
${}直接拼接 ,不会转换类型
如果是简单类型,必须写${value}如果是pojo类型,${属性名}(注意:需要转换类型)
#{}相当于占位符,可以自动的转换类型 可以防止SQL注入
如果是简单类型,可以随便写${随便写}如果是pojo类型,${属性名}(注意:可以自动转换类型)
一、# “%”#{value}"%"
1.UserMapper.xml
<select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like "%"#{value}"%"</select>
2.TestMybatis
/*** 模糊查询* 通过用户名字模糊查询*/@Testpublic void findByUsername(){InputStream inputStream = Resources.class.getClassLoader().getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> selectList = sqlSession.selectList("com.william.mapper.UserMapper.findByUsername","a");for (Object o : selectList) {System.out.println(o);}sqlSession.close();}
3.测试结果
执行的SQL语句
Preparing: select * from user where username like "%"?"%" Parameters: a(String)
二、$ ‘%${value}%’
1.UserMapper.xml
<!--模糊查询--><select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like '%${value}%'</select>
2.TestMybatis
/*** 模糊查询* 通过用户名字模糊查询*/@Testpublic void findByUsername(){InputStream inputStream = Resources.class.getClassLoader().getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> selectList = sqlSession.selectList("com.william.mapper.UserMapper.findByUsername","a");for (Object o : selectList) {System.out.println(o);}sqlSession.close();}
3.测试结果
执行的SQL语句
Preparing: select * from user where username like '%a%' Parameters:
三、在测试类参数中添加
1.UserMapper.xml
<select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like #{abc}</select>
2.TestMybatis
/*** 模糊查询* 通过用户名字模糊查询*/@Testpublic void findByUsername(){InputStream inputStream = Resources.class.getClassLoader().getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> selectList = sqlSession.selectList("com.william.mapper.UserMapper.findByUsername","%a%");for (Object o : selectList) {System.out.println(o);}sqlSession.close();}
3.测试结果
执行的SQL语句
Preparing: select * from user where username like ? Parameters: %a%(String)