Spring jdbcTemplate 动态 where 子句

9

通过JDBC模板,是否可以生成任意的where条件SQL查询?

示例:

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

"select * from address where shopname = ?";

如果我传递了两个参数的值(名称和城市)- 按商店名称和城市搜索:
"select * from address where shopname = ? and city = ?";

我有多个搜索字段,共7个。如果用户输入任何组合,我只能基于参数进行搜索。

如何动态传递参数到SQL?
需要代码片段/示例来实现此操作。

5个回答

11
您需要的是某种标准构建 API,Hibernate具有此功能。不幸的是,我认为Spring的JdbcTemplate没有这样的设施。如果我错了,其他人可以纠正我...

3
尽管一些人已经建议使用Hibernate是做这件事的最佳方式,但我认为您可以尝试以下方法-
String sql = "select * from address where 1 = 1";

if(shopname != null)
  sql += "and shopname = :shopname";

if(city!= null)
  sql += "and city = :city";

等等,使用NamedParameterJdbcTemplate


2
使用StringBuilder()代替字符串串联 :) - Slava Semushin

0

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)";

0
如果您正在使用 Kotlin,可以像这样构建查询:
fun optParamStr(param: Any?, queryParamName: String): String? =
        param?.let { "$queryParamName = :$queryParamName" }


val params = listOf(
                value1 to filed1,
                value2 to field2,
                value3 to field3
            ).mapNotNull { optParamStr(it.first, it.second) }.joinToString(" AND ")

我看不出与Spring JDBCtemplate的联系。 - greybeard

-3
如果您可以选择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

1
我不熟悉Scala,但从这种建议方法中的字符串连接来看,我建议避免使用此方法以避免可能的SQL注入攻击。 - Kevin Hooke
1
由于 SQL 注入风险,这样做非常不安全。 - BrianC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接