java Spring JdbcTemplate:如何限制选定的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9941488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring JdbcTemplate: how to limit selected rows?
提问by davioooh
I'm using Spring JdbcTemplate
interface for fetching data from a MS SqlServer DB.
In the documentation I see there is the setMaxRows()
method to set a limit for all the queries, but what if I want to limit only a select?
我正在使用 SpringJdbcTemplate
接口从 MS SqlServer DB 获取数据。在文档中我看到有为setMaxRows()
所有查询设置限制的方法,但是如果我只想限制一个选择怎么办?
Is there a way to set a limit only for a specific invoked query in a "configurable" way?
有没有办法以“可配置”的方式仅为特定调用的查询设置限制?
采纳答案by jabal
Limiting the result set of a specific query can be done by putting the limit directly into the query. Consult your DB vendor documentation to see if it supports for example LIMIT
.
可以通过将限制直接放入查询来限制特定查询的结果集。例如,请查阅您的数据库供应商文档以查看它是否支持LIMIT
。
Example on MySQL: SELECT * FROM EMPLOYEE LIMIT 10
MySQL 上的示例: SELECT * FROM EMPLOYEE LIMIT 10
回答by Buru
Some SQL based query languages(derby) doesn't support LIMIT
keyword. So you can't use LIMIT in query directly. Using Spring JDBC Template we can set maximum number of rows needed through setMaxRows(Integer intvalue)
一些基于 SQL 的查询语言(derby)不支持LIMIT
关键字。所以你不能直接在查询中使用 LIMIT 。使用 Spring JDBC 模板,我们可以设置所需的最大行数setMaxRows(Integer intvalue)
jdbcTemplate.setMaxRows(1);
回答by Musaddique
You can also user limit keyword in query. see below query
您还可以在查询中使用限制关键字。见下面的查询
select * from FileShare limit 3 offset 3
if in your application limit and offset can be assign dynamically by user the use below query
如果您的应用程序中的限制和偏移量可以由用户动态分配,请使用以下查询
@Autowired
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return HibernateUtil.getJdbcTemplate();
}
public List<FileShare> getAllSharedFiless(int limit,int offset)
throws ShareMeException {
String query="select * from FileShare limit ? offset ?";
return getTemplate().query(query,
new SharedFilesRowMapper(),
new Object[]{limit,offset});
}
Here FileShare
is a table name and SharedFilesRowMapper
is rowMapper which list rows from table.
这FileShare
是一个表名,SharedFilesRowMapper
是 rowMapper,它列出了表中的行。
回答by Asgar
setFetchSize
or setMaxRows
is not the same as LIMIT
in DB SQL. Setting fetch size
in JdbcTemplate
means that the resultset of your query will be fetched in chunks of the size set with setFetchSize
. This is to control the memory usage and the number of database calls.
setFetchSize
或setMaxRows
与LIMIT
DB SQL 中的不同。设置fetch size
inJdbcTemplate
意味着您的查询的结果集将以setFetchSize
. 这是为了控制内存使用和数据库调用次数。