zoukankan      html  css  js  c++  java
  • String.format VS. StrSubstitutor VS. NamedParameterJdbcTemplate

      在Java中,想要用一个字符串模块根据参数的不同来产生不同的字符串,主要有以下两种办法:

      Java String.format()


         在JDK1.5中,String类新增了一个很有用的静态方法String.format().
         format(Locale l, String format, Object... args) 使用指定的语言环境、格式字符串和参数返回一个格式化字符串;
         format(String format, Object... args) 使用指定的格式字符串和参数返回一个格式化字符串。
         在格式化字符串中,大部分参数都比较符合C风格中的printf()函数,但是需要注意的是,在Java中,有一个可选的argument_index的十进制的参数,用来表明参数在参数列表中的位置。第一个由“1$”引用,第二个由“2$”引用,以此类推。例如:

    System.out.println(String.format("%s,%s,%1$s,%2$s,%1$s", "a", "b"));   
    
    //输出:a,b,a,b,a

      Commons-lang StrSubstitutor


         在Commons-lang中,给我们提供一个新的类叫做StrSubstitutor,专门用来做一些字符串替换填充的事情。例如:

    Map valuesMap = HashMap();
    valuesMap.put("animal", "quick brown fox");
    valuesMap.put("target", "lazy dog");
    String templateString = "The ${animal} jumped over the ${target}.";
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    String resolvedString = sub.replace(templateString);
    
    //输出:The quick brown fox jumped over the lazy dog.

      联想到的NamedParameterJdbcTemplate


      这使我想起了曾经在使用JdbcTemplate的时候,SQL语句的参数都是用“?”作为占位符,严重依赖于顺序。为了解决这个问题,我们可以选择使用Spring中的NamedParameterJdbcTemplate。这样我们就可以使用“:”跟上变量名而不用依赖位置的先后顺序了,而且可读性也大大提高了。例如:

    //insert with named parameter
    public void insertNamedParameter(Customer customer){
        String sql ="INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)";
        Map<String, Object]]> parameters =new HashMap<String, Object]]>();
        parameters.put("custId", customer.getCustId());
        parameters.put("name", customer.getName());
        parameters.put("age", customer.getAge());
        getSimpleJdbcTemplate().update(sql, parameters);
    }

      

  • 相关阅读:
    全体自然数的和是负十二分之一?
    隐马尔可夫模型(二)维特比算法
    隐马尔可夫模型
    freemarker实现单元格动态合并-行合并
    工具类_JavaPOI_Office文件内容读取
    SpringBoot-自动装配对象及源码ImportSelector分析
    SpringBoot-文件在线预览解决方案-基于OpenOffice及jacob
    Elasticsearch6.4.0-windows环境部署安装
    单列模式与多线程
    基于SpringMVC的文件(增删改查)上传、下载、更新、删除
  • 原文地址:https://www.cnblogs.com/penghongwei/p/3442067.html
Copyright © 2011-2022 走看看