07.mybatis参数传值占位符

一、#占位符

#占位符告诉mybatis使用实际的参数值代替,#{…}代替sql语句的"?"。这样做更安全,更迅速,通常也是首选做法。

                insert into student(id, stu_name, age, address, stu_clazzno)        values (#{id}, #{name}, #{age}, #{address}, #{clazzno})    

#{}占位符的特点:

① 使用PrepareStatement对象执行sql语句

② 使用PrepareStatement对象,能避免sql注入,sql语句执行更安全

③ #{}常常作为列值使用的,位于等号的右侧,#{}位置的值和数据类型有关的;

④ 如果只有传递一个参数,占位符的名字和后面的名字可以不一样,如果多个参数,需要使用@Param指定传的值对应的参数;

(2) 占位符${}

表示字符串连接,把‘sql‘语句的其他内容和{}内容使用字符串(+) 连接的方式连在一起;

    /**     * 根据姓名您查询学生信息     * @param name 学生姓名     * @return     */    public List selectStudentsByName(@Param("stuName") String name);
@Test    public void selectStudentsByName() {        //读取配置文件到数据流        InputStream stream = Student.class.getClassLoader().getResourceAsStream("mybatis-config.xml");        //创建SqlSessionFactory        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);        //创建SqlSession        //openSession(true) 表示提交事务        SqlSession sqlSession = sqlSessionFactory.openSession(true);        //获取StudentMapper        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);        //执行查询数据方法        List studentList = mapper.selectStudentsByName("小明");        //打印结果        studentList.forEach(student -> System.out.println(student));    }

${}的特点

① 使用Statement对象,执行sql语句,效率低;

② ${}占位符的值,使用的字符串连接方式,有sql注入的风险。有代码安全的问题;

③ ${}数据是原样使用的,不会区分数据类型;

④ 常用作表名或者列明,在能保证数据安全的情况下使用 {};

⑤ 如果使用${}由于是字符串拼接,在查询条件的时候需要加上单引号,要不然会报错,#{}由于是占位符,会自动填充,无需加上单引号;

(3) #{}和${}组合使用

有时候我们单独的使用#{}或者${}都不能很好的解决问题,比如下面这个例子,我们要从指定的数据中查询名字为XXX的数据,并且按照姓名进行降序排序;

    /**     * 根据姓名查询学生数量     * @param tableName 待查询表的名称     * @param sutName 学生姓名     * @return     */    public Integer selectCountByName(@Param("tableName") String tableName,                                     @Param("sutName") String sutName);
@Testpublic void selectCountByName(){    //读取配置文件到数据流    InputStream stream = Student.class.getClassLoader().getResourceAsStream("mybatis-config.xml");    //创建SqlSessionFactory    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);    //创建SqlSession    //openSession(true) 表示提交事务    SqlSession sqlSession = sqlSessionFactory.openSession(true);    //获取StudentMapper    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);    //执行查询数据方法    Integer integer = mapper.selectCountByName("student", "小");    //打印结果    System.out.println("integer = " + integer);}

${}一般用于字符串表或者字段等,用于拼接;#{}一般用于传值,效率高,通常情况下使用#{}是首选;

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章