今天我们来学习mybatis实现模糊查询

1.第一种方式

第一种方式:在java程序中,把like的内容组装好,把这个内容传入到sql语句

我们先在dao接口中定义一个方法

//like的第一种方式
List<Student> selectLikeOne(@Param("name") String name);

mapper文件中:

<!--like第一种方式-->
<select id="selectLikeOne" resultType="com.lu.entity.Student">
	select * from student where name like #{name}
</select>

测试类中进行测试

@Test
public void testLikeOne() {
    SqlSession session = MyBatisUtil.getSqlSession();
    StudentDao dao = session.getMapper(StudentDao.class);

    String name = "%张%";
    List<Student> students = dao.selectLikeOne(name);
    session.close();

    students.forEach(student -> System.out.println(student));
}

控制台输出:

2.第二种方式

第二种方式:在sql语句,组织like的内容

sql语句like的格式:where name like “%“空格#{name}空格”%”

步骤:

在dao接口中定义方法:

//like的第二种方式
List<Student> selectLikeTwo(@Param("name") String name);

在mapper文件中:

<!--like第二种方式-->
<select id="selectLikeTwo" resultType="com.lu.entity.Student">
	select * from student where name like "%" #{name} "%"
</select>

在测试类中测试:

@Test
public void testLikeTne() {
	SqlSession session = MyBatisUtil.getSqlSession();
	StudentDao dao = session.getMapper(StudentDao.class);

	String name = "张";
	List<Student> students = dao.selectLikeTwo(name);
	session.close();

	students.forEach(student -> System.out.println(student));
}

控制台输出:

更多推荐

MyBatis实现模糊查询