字符串中占位符替换-mybatis学习笔记

  1. 编写TokenHandler实现类(从输入参数中获取value替换sql中的占位符,这里使用Map承载)
    private static class VariableTokenHandler implements TokenHandler {
           
      private Map<String, String> variables = new HashMap<>();
      private VariableTokenHandler(Map<String, String> variables) {
           
          this.variables = variables;
      }
      @Override
      public String handleToken(String content) {
           
          String value = variables.get(content);
          if (StringUtils.isEmpty(value)){
           
              return null ;
          }else {
           
              return "'"+value+"'" ;
          }
      }
    }
    
  2. 整理输入参数到Map对象中
    Map<String,String> params = new HashMap<>() ;
    params.put("name","zhangsan") ;
    params.put("age","18") ;
    
  3. 编写字符串模板
    String sqlTemplate = "insert into user(username,age,sequence) values(${name},${age},myseq.nextval)" ;
    
  4. 根据输入参数和字符串模板替换
    VariableTokenHandler handler = new VariableTokenHandler(params);
    // 替换sql模板中的${xxx}占位符
    GenericTokenParser parser = new GenericTokenParser("${", "}", handler);
    String retContent = parser.parse(sqlTemplate);
    
  5. 输出结果
    System.out.println(retContent);
    // 输入结果:
    insert into user(username,age,sequence) values('zhangsan','18',myseq.nextval)
    

你可能感兴趣的:(mybatis,java)