【问题标题】:Spring jdbcTemplate dynamic where clauseSpring jdbcTemplate 动态 where 子句
【发布时间】:2011-05-22 15:36:37
【问题描述】:

是否可以通过Jdbc模板生成任意where条件SQL查询:

示例:

如果我为 1 个参数(仅名称)传递值:按名称搜索

"select * from address where shopname = ?";

如果我为 2 个参数(名称和城市)传递值 - 按商店名称和城市搜索:

"select * from address where shopname = ? and city = ?";

我有多个搜索字段。 7 个字段。如果用户输入任何组合。我只根据参数进行搜索。如何动态地将参数传递给sql。需要 sn -p/Example 如何实现。

【问题讨论】:

    标签: spring jdbctemplate


    【解决方案1】:

    您想要的是某种标准构建 api,它是 Hibernate 所拥有的。不幸的是,我不认为 Spring 的 JdbcTemplate 有任何这样的功能。如果我错了,其他人会纠正我...

    【讨论】:

      【解决方案2】:

      虽然有些人已经建议 Hibernate 是最好的方法,但我仍然认为你可以尝试这种方法-

      String sql = "select * from address where 1 = 1";
      
      if(shopname != null)
        sql += "and shopname = :shopname";
      
      if(city!= null)
        sql += "and city = :city";
      

      等等..并使用 NamedParameterJdbcTemplate

      【讨论】:

      • ... 并使用 StringBuilder() 代替字符串连接 :)
      【解决方案3】:

      Spring Data 和 Hibernate 具有这种功能。尽管为您的应用程序拖入如此大的框架可能不值得。

      您可以尝试查看 SimpleJdbcInsert http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html

      编辑: 或者,您可以尝试在 SQL 中通过检查空来修复它,但如果您有大量数据要处理,这种技术会减慢您的请求。

      "select * from address 
      where (shopname = ? or shopname = null)
       and (city = ? or city = null)";
      

      【讨论】:

        【解决方案4】:

        如果您可以选择 Scala,则可以使用以下方式构造查询:

        case class Search(shopname:String, city:String = None) {
         def sql = "select * from address where shopname = '"+shopname+"'" + city.map(" and city = '"+
              _ +"'").getOrElse("")  
        }
        

        示例用法:

        Search("lloh").sql
        Search("lloh", Some("Austin")).sql
        

        【讨论】:

        • 我不熟悉 Scala,但是从这个建议方法中的字符串连接来看,我建议避免这种方法以避免 SQL 注入攻击的可能性。
        • 由于 SQL 注入风险,这将是非常不安全的。
        猜你喜欢
        • 2020-06-19
        • 1970-01-01
        • 2015-09-20
        • 2016-11-26
        • 2019-10-12
        • 2016-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多