---
title: "MyBatis模糊查询"
author: "onlyor"
date: "2012-09-14T13:56:32Z"
tags: []
categories: ["编程语言"]
slug: "mybatis"
draft: false
lastmod: "2012-09-14T13:56:32Z"
id: 1678501
url: "https://onlyor.iteye.com/blog/1678501"
---

## MyBatis模糊查询

(2012-02-04 12:36:13) [![](http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif) 转载 *▼*]()

映射文件：

 

&lt;select id="selectStudentByName" parameterType="String" resultType="Student"&gt;  
  select s\_id,s\_name,s\_age  
  from student  
  where s\_name like '%'||#{s\_name}||'%'  
 &lt;/select&gt;

 

此方法在mybatis-3.1.0测试通过

\-----------------------------------------------------

public List&lt;Student&gt; queryStudentsByName(String name) {  
  List&lt;Student&gt; students;  
  try{  
   sqlSession = sf.openSession();  
   students = sqlSession.selectList("selectStudentByName", name);  
  }finally{  
   sqlSession.close();  
  }  
  return students;  
 }

\------------------------------------------------------

@Test  
 public void queryStudentsByNameTest(){  
  IStudentDAO sDAO = new IStudentDAOIbatisImpl();  
  for(Student stu :sDAO.queryStudentsByName("x")){  
   System.out.println(stu);  
  }  
 }

 

如果是ibatis：

select s\_id,s\_name,s\_age

from student

where s\_name like '%$s\_name$%'

\-------------------------------------------------------

 

模糊查询的实现 两种方式：

一：在sql语句里写 % %

二：在参数中写 "%xxx%"

 

&lt;select id="selectStudentByName" parameterType="String" resultType="Student"&gt;  
  select s\_id,s\_name,s\_age  
  from student  
  where s\_name like #{s\_name}  
 &lt;/select&gt;

 

@Test  
 public void queryStudentsByNameTest(){  
  IStudentDAO sDAO = new IStudentDAOIbatisImpl();  
  for(Student stu :sDAO.queryStudentsByName("%x%" )){  
   System.out.println(stu);  
  }  
 }

 

在mybatis-3.1.0测试通过