模糊查詢三種解決方式


模糊查詢

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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM