模糊查询三种解决方式
模糊查询
1.${}:原样输出,不能防止sql注入
#{}:自动拼接引号
2.传值时,直接传
student.setStuName("%s%");
stuName like #{stuName}
3.bind参数
src\org\myy\mapper\studentMapper.xml
通过bind将传入的stuName进行了处理(增加了%...%)
<select id="queryStudentByNoWithONGL" parameterType="student" resultType="student"> select * from student1 <trim prefix="where" suffixOverrides="and"> <bind name="_queryName" value="'%'+stuName+'%'" /> <if test="_parameter.stuName != null and _parameter.stuName != '' "> stuName like #{_queryName} and </if> <if test="graName != null and graName != '' "> graName like '%${graName}%' and </if> <if test="stuAge != null and stuAge != '' "> stuAge = #{stuAge} and </if> </trim> </select>
src\org\myy\mapper\StudentMapper.java
List<Student> queryStudentByNoWithONGL(Student student);
src\org\myy\test\Test.java
//Connection - SqlSession操作Mybatis //conf.xml->reader Reader reader = Resources.getResourceAsReader("conf.xml"); //reader->sqlSession //可以通过build的第二参数 指定数据库环境 SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader,"devOracle"); SqlSession session = sessionFactory.openSession(); StudentMapper studentMapper=session.getMapper(StudentMapper.class); //Student student=new Student("s",23,"b"); Student student=new Student(); student.setStuName("s"); student.setStuAge(23); List<Student> students=studentMapper.queryStudentByNoWithONGL(student); System.out.println(students); session.close();
be simple, be happy.