介绍

中文名:对象图导航语言,通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。它使用相同的表达式去存取对象的属性。这样可以更好的取得数据。主要是#、%和$这三个符号的使用。

为什么要学

他与mybatis有关,mybatis在如下两个地方应用到了 ognl表达式
动态SQL表达式中
${param}参数中

使用

动态传递参数

  1. select * from user where name = #{name};
  2. select * from user where name = ${name};

#和$的区别

{ }:解析为一个 JDBC 预编译语句(prepared statement)的参数标记符。
会动态解析为占位符

  1. select * from user where name = ?;

${ }: 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。
如 传递参数为“jack”

  1. select * from user where name = "Jack";

守则:

  1. 能用 #{} 不用${} 性能原因 sql注入问题
  2. 表名作变量必须用${} sql占位符进行变量替换时会加上单引号 sql中表名不能有单引号

    sql动态语句例子

    mybatis注释方式中动态语句中update函数

    1. public String update(TPersonInfo person){
    2. return new SQL(){
    3. {
    4. UPDATE("T_PERSON_INFO");
    5. if(person.getName() != null){
    6. SET("name=#{name}");
    7. }
    8. if(person.getAge() != null){
    9. SET("age=#{age}");
    10. }
    11. WHERE("id=#{id}");
    12. }
    13. }.toString();
    14. }

    select函数

    1. public String select(Map<String,Object> map){
    2. return new SQL(){
    3. {
    4. SELECT("*");
    5. FROM("T_PERSON_INFO");
    6. StringBuilder whereClause = new StringBuilder();
    7. if(map.get("name") != null){
    8. whereClause.append(" and name like '%").append(map.get("name")).append("%' ");
    9. }
    10. if(map.get("age") != null){
    11. whereClause.append(" and age = ").append(map.get("age"));
    12. }
    13. if(!"".equals(whereClause.toString())){
    14. WHERE(whereClause.toString().replaceFirst("and", ""));
    15. }
    16. }
    17. }.toString();
    18. }

    作者:cccccttttyyy
    链接:https://www.jianshu.com/p/6bc6752d11f4
    来源:简书