Java教程

【MyBatis】学习笔记07:模糊查询

本文主要是介绍【MyBatis】学习笔记07:模糊查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

【Mybatis】学习笔记01:连接数据库,实现增删改

【Mybatis】学习笔记02:实现简单的查

【MyBatis】学习笔记03:配置文件进一步解读(非常重要)

【MyBatis】学习笔记04:配置文件模板

【MyBatis】学习笔记05:获取参数值的两种方式

【MyBatis】学习笔记06:各种查询所返回数据的数据类型

目录
  • 写法1:$
  • 写法2:concat拼接
  • 写法3:#(推荐使用)

写法1:$

    /**
     * 根据用户名模糊查询
     * @param username 用户名的关键字
     * @return  List<User> 用户列表
     */
    List<User> getUserByLike(@Param("username") String username);
<!--    List<User> getUserByLike(@Param("username") String username);-->
    <select id="getUserByLike" resultType="User">
         select * from t_users where userName like "%${username}%"
    </select>
    @Test
    public void testGetUserByLike(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
        List<User> list = mapper.getUserByLike("三");
        System.out.println(list);
    }
[User{userId='5',userName='张三'userCount='mllt@xrilang.com',userPassword='123'userGrade='0',userRegDate='null'userBlance='0'}, User{userId='6',userName='李三'userCount='xirlang@mllt.c',userPassword='124'userGrade='0',userRegDate='null'userBlance='0'}]

写法2:concat拼接

<!--    List<User> getUserByLike(@Param("username") String username);-->
    <select id="getUserByLike" resultType="User">
         <!-- select * from t_users where userName like "%${username}%"-->
        select * from t_users where userName like concat("%",#{username},"%")
    </select>
<!--concat 拼接-->
[User{userId='5',userName='张三'userCount='mllt@xrilang.com',userPassword='123'userGrade='0',userRegDate='null'userBlance='0'}, User{userId='6',userName='李三'userCount='xirlang@mllt.c',userPassword='124'userGrade='0',userRegDate='null'userBlance='0'}]

写法3:#(推荐使用)

<!--    List<User> getUserByLike(@Param("username") String username);-->
    <select id="getUserByLike" resultType="User">
         <!-- select * from t_users where userName like "%${username}%"-->
         <!-- select * from t_users where userName like concat("%",#{username},"%")-->
        select * from t_users where userName like "%"#{username}"%"
</select>
[User{userId='5',userName='张三'userCount='mllt@xrilang.com',userPassword='123'userGrade='0',userRegDate='null'userBlance='0'}, User{userId='6',userName='李三'userCount='xirlang@mllt.c',userPassword='124'userGrade='0',userRegDate='null'userBlance='0'}]
这篇关于【MyBatis】学习笔记07:模糊查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!