Mybatis的 #{ }与${ }

一般在mybatis中使用#{ }代替参数,相当于占位符,#{}可以获取参数值,或者POJO对象属性的值。

   #{}:相当于占位符,是以预编译的形式,将参数设置到sql语句中,PreparedStatement;防止sql注入
  ${}:相当于拼接符,取出的值直接拼装在sql语句中,会有安全问题;
    大多情况下,我们取参数的值都应该去使用#{};

但在某些情况下,就需要使用${ } 

  

  原生JDBC不支持占位符的地方我们就可以使用${}进行取值
  比如分表、排序;按照年份分表拆分
    select * from ${year}_salary where xxx;[表名不支持预编译]
    select * from tbl_employee order by ${f_name} ${order} :排序是不支持预编译的!

  模糊查询:

下面看一个例子:

  Java接口:

public List<Student> findStu(Student student);

  xml文件:

  SQL语句: select * from stu1 where sname like '%x%'

  在这里需要注意,使用${}获取POJO 中String类型属性值,值为英文字母或汉字的,需要在${} 的两边加上单引号

  这里加上%%的用途是,%是拼接符,前后匹配任意个字符,也需要在单引号内。

<!--public List<Student> findStu(String sname); -->
    <select id="findStu" parameterType="com.neuedu.bean.Student"
        resultType="com.neuedu.bean.Student">
        select * from stu1 where sname like '%${sname}%'

    </select>

  在这里也可以使用concat(str1,str2,str3,......)函数,此函数是连接字符串函数,会生成一个字符串

<!--public List<Student> findStu(String sname); -->
    <select id="findStu" parameterType="com.neuedu.bean.Student"
        resultType="com.neuedu.bean.Student">
        select * from stu1 where sname like concat("'%",#{sname},"%'")
 

    </select>

 测试类

@Test
    public void testUpdate(){
        Student student=new Student(1, "xiaosheng","100", "1");
        try {
            SqlSessionFactory sqlSessionFactory = sqlSessionFactory();
            SqlSession openSession = sqlSessionFactory.openSession();
            Stu mapper = openSession.getMapper(Stu.class);
            mapper.updateStuById(student);
            openSession.commit();
            openSession.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

切记如果值为字母或汉字需要加上单引号。当然以防万一,可以在${}的两边都加上单引号,这里${}在获取POJO属性值的时候需要加上单引号,在获取非POJO属性的值

的时候就不需要加单引号。

下面看打印的日志:

DEBUG 09-04 20:32:05,148 ==> Preparing: update stu1 set sname='xiaosheng', score=100,sclass=1 where sid=1 (BaseJdbcLogger.java:145)
DEBUG 09-04 20:32:05,311 ==> Parameters: (BaseJdbcLogger.java:145)

原文地址:https://www.cnblogs.com/xuesheng/p/7475528.html