MyBatis模糊查询详解(3种主流写法语句)

MyBatis模糊查询详解(3种主流写法语句)-mikechen

mybatis模糊查询使用频率很高,下面重点详解mybatis模糊查询的3种主流方式写法语句。

第一种:直接将封装好的条件传给 sql 语句

1.增加配置

  1. <!-- 根据姓名查询学生信息-->
  2. <select id="selectStuByName" resultType="com.mikechen.mybatis.domain.Student">
  3. select * from student where name like #{name}
  4. </select>

 

2.调用接口

  1. /**
  2. * 根据姓名模糊查询学生信息
  3. * @param name 学生名字
  4. * @return
  5. */
  6. public List<Student> selectStuByName(@Param("name") String name);

 

3.代码实现

  1. @Test
  2. public void testLikeOne() {
  3. // 读取配置文件到数据流
  4. InputStream stream = Student.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
  5. // 创建SqlSessionFactory
  6. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
  7. //创建SqlSession
  8. SqlSession sqlSession = sqlSessionFactory.openSession();
  9. //获取StudentMapper
  10. StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
  11. //执行查询语句
  12. String name = "%小%";
  13. List<Student> students = mapper.selectStuByName(name);
  14. }

 

第二种:使用字符串连接符 ${} 来实现

1.增加配置

根据姓名查询学生信息,如下所示:

  1. <select id="selectStuByName" resultType="com.mikechen.mybatis.domain.Student">
  2. select * from student where name like "%" #{name} "%"
  3. </select>

 

2.代码实现

  1. @Test
  2. public void testLike() {
  3. //读取配置文件到数据流
  4. InputStream stream = Student.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
  5.  
  6. //创建SqlSessionFactory
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
  8.  
  9. //创建SqlSession
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11.  
  12. //获取StudentMapper
  13. StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
  14.  
  15. //执行查询语句
  16. String name = "小";
  17. List<Student> students = mapper.selectStuByName(name);
  18.  
  19. }

 

第三种:使用 mysql 的字符串拼接函数实现

1.增加配置

  1. <select id="findByName" parameterType="string" resultType="User">
  2. select * from t_user where name like concat(#{name},'%')
  3. </select>

 

2.代码实现

  1. @Test
  2. public void testFindLike() throws IOException{
  3. SqlSession session = MybatisUtil.getSqlSession();
  4. List<User> list = session.selectList("cn.mikechen.vo.UserMapper.findByName","张");
  5. for(User u:list){
  6. System.out.println(u);
  7. }
  8. session.close();
  9. }

 

评论交流
    说说你的看法
欢迎您,新朋友,感谢参与互动!