您的位置 首页 java

10.mybatis模糊查询

mybatis实现模糊查询,主要有两种方式:

一、方法一

java 程序中,把like的内容组装好,把这个内容传入到 sql语句

 /**
 * 根据姓名模糊查询学生信息
 * @param name 学生信命
 * @return
 */public  List<Student> selectStuByName(@Param("name")  String  name);  
 <!--    根据姓名查询学生信息-->
<select id="selectStuByName" resultType="com.jiaguohui. mybatis .domain.Student">
    select * from student where name like #{name}
</select>
  
 @Test
public  void  testLikeOne() {
    //        读取配置文件到数据流
    InputStream stream = Student.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
    //        创建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
    //创建SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获取StudentMapper
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    //执行查询语句
    String name = "%小%";
    List<Student> students = mapper.selectStuByName(name);
    //打印结果
    students.forEach(student -> System.out.println(student));
}  

二、方法二

在sql语句,组织like的内容,sql语句like的格式:where name like “%“空格#{name}空格”%”

也可以使用这种方式;

 /**
 * 根据姓名模糊查询学生信息
 * @param name 学生信命
 * @return
 */public  List<Student> selectStuByName(@Param("name") String name);
  
 <!--    根据姓名查询学生信息-->
<select id="selectStuByName" resultType="com.jiaguohui.mybatis.domain.Student">
    select * from student where name like "%" #{name} "%"
</select>  
 @Test
public void testLikeOne() {
    //        读取配置文件到数据流
    InputStream stream = Student.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
    //        创建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
    //创建SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获取StudentMapper
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    //执行查询语句
    String name = "小";
    List<Student> students = mapper.selectStuByName(name);
    //打印结果
    students.forEach(student -> System.out.println(student));
}  

三、特别注意

也可以使用如下方式处理like查询:

1.针对 Mysql数据库 :like concat(‘%’,#{name},’%’)

 <!--    根据姓名查询学生信息-->
<select id="selectStuByName" resultType="com.jiaguohui.mybatis.domain.Student">
    select * from student WHERE name like concat('%',#{name},'%')
</select>  

2.针对 Oracle数据库 :concat(concat(‘%’,#{syqr}),’%’)

 <!--    根据姓名查询学生信息-->
<select id="selectStuByName" resultType="com.jiaguohui.mybatis.domain.Student">
    select * from student WHERE name like  concat(concat('%',#{syqr}),'%')
</select>  

文章来源:智云一二三科技

文章标题:10.mybatis模糊查询

文章地址:https://www.zhihuclub.com/194811.shtml

关于作者: 智云科技

热门文章

网站地图