Spring jdbcTemplate 动态 where 子句
是否可以通过JDBC模板生成任意where
条件的SQL查询?
示例:
如果我传递 1 个参数的值(仅名称):按名称搜索
"select * from address where shopname = ?";
如果我传递 2 个参数的值(名称和城市) - 按商店名称和城市搜索:
"select * from address where shopname = ? and city = ?";
我有多个搜索字段。 7 个字段。如果用户输入任何组合。我仅根据参数进行搜索。
如何动态传递参数给SQL?
需要片段/示例如何实现这一目标。
Is it possible to generate arbitrary where
conditions SQL query through JDBC template?
example:
If I pass value for 1 parameter (only name) : search by name
"select * from address where shopname = ?";
If I pass value for 2 parameter (name and city) - search by shopname and city:
"select * from address where shopname = ? and city = ?";
I have multiple search fields. 7 fields. If user enters any combination. I have search only based on parameter.
How to dynamically pass the parameters to the SQL?
Need snippet/Example how to achieve this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你想要的是某种构建 api 的标准,Hibernate 就有。不幸的是,我认为 Spring 的 JdbcTemplate 没有任何这样的功能。如果我错了,其他人会纠正我...
What you want is some sort of criteria building api, which Hibernate has. Unfortunately, I don't think Spring's JdbcTemplate has any such facility. Others will correct me if I'm wrong...
尽管有些人已经建议 Hibernate 是执行此操作的最佳方法,但我仍然认为您可以尝试这种方法 -
依此类推..并使用 NamedParameterJdbcTemplate
Though as some guys already suggested that Hibernate is the best way of doing this, but still i think you can try this approach-
and so on..and use NamedParameterJdbcTemplate
Spring Data 和 Hibernate 具有此类功能。尽管可能不值得为您的应用程序拖入这么大的框架。
您可以尝试查看 SimpleJdbcInsert
http://docs.spring.io/spring /docs/current/spring-framework-reference/html/jdbc.html
编辑:
或者,您可以尝试在 SQL 中通过检查空来修复它,但如果您有大量数据需要处理,这种技术会减慢您的请求。
Spring Data and Hibernate have that kind of functionality. Though it might not be worth dragging in such big framework for your app.
You can try to check out SimpleJdbcInsert
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html
Edit:
Alternatively you can try to fix it in SQL with checking on empty, but if you have lots of data to go through, this technique will slow down your request.
如果您使用 Kotlin,则可以按如下方式构造查询:
If you are using Kotlin, the query could be constructed like this:
如果您可以选择 Scala,则可以使用如下方式构建查询:
示例用法:
If Scala is an option to you, the query could be constructed with something like this:
Example usage: