spring-data


How to limit the result with #Query? [duplicate]


I am trying to incorporate Spring-Data-JPA to my project.
One thing confuses me is how to achieve setMaxResults(n) by annotation ?
for example , my code:
public interface UserRepository extends CrudRepository<User , Long>
{
#Query(value="From User u where u.otherObj = ?1 ")
public User findByOhterObj(OtherObj otherObj);
}
I only need to return one (and only one) User from otherObj , but I cannot find a way to annotate the maxResults ... Can somebody give me a hint ?
(mysql complains :
com.mysql.jdbc.JDBC4PreparedStatement#5add5415: select user0_.id as id100_, user0_.created as created100_ from User user0_ where user0_.id=2 limit ** NOT SPECIFIED **
WARN util.JDBCExceptionReporter - SQL Error: 0, SQLState: 07001
ERROR util.JDBCExceptionReporter - No value specified for parameter 2
)
I found a link : https://jira.springsource.org/browse/DATAJPA-147 ,
I tried but failed. It seems not possible now ?
Why such a important feature not built in Spring-Data ?
If I implement this feature manually :
public class UserRepositoryImpl implements UserRepository
I have to implement tons of predefined methods in CrudRepository , this will be terrible.
environments : spring-3.1 , spring-data-jpa-1.0.3.RELEASE.jar , spring-data-commons-core-1.1.0.RELEASE.jar
As of Spring Data JPA 1.7.0 (Evans release train).
… you can use the newly introduced Top and First keywords that allow you to define query methods like these:
findTop10ByLastnameOrderByFirstnameAsc(String lastname);
Spring Data will automatically limit the results to the number you defined (defaulting to 1 if omitted). Note, that the ordering of the results becomes relevant here (either through an OrderBy clause as seen in the example or by handing a Sort parameter into the method). Read more on that in the blog post covering new features of the Spring Data Evans release train or in the documentation.
For previous versions
To retrieve only slices of data Spring Data uses the pagination abstraction which comes with a Pageable interface on the requesting side as well as a Page abstraction on the result side of things. So you could start with
public interface UserRepository extends Repository<User, Long> {
List<User> findByUsername(String username, Pageable pageable);
}
and use it like this:
Pageable topTen = new PageRequest(0, 10);
List<User> result = repository.findByUsername("Matthews", topTen);
If you need to know the context of the result (which page is it actually? is it the first one? how many are there in total?) use Page as return type:
public interface UserRepository extends Repository<User, Long> {
Page<User> findByUsername(String username, Pageable pageable);
}
The client code can then do something like this:
Pageable topTen = new PageRequest(0, 10);
Page<User> result = repository.findByUsername("Matthews", topTen);
Assert.assertThat(result.isFirstPage(), is(true));
Not that we will trigger a count projection of the actual query to be executed in case you use Page as return type as we need to find out how many elements there are in total to calculate the metadata. Beyond that be sure you actually equip the PageRequest with sorting information to get stable results. Otherwise you might trigger the query twice and get different results even without the data having changed underneath.
If you are using Java 8 and Spring Data 1.7.0, you can use default methods if you want to combine a #Query annotation with setting maximum results:
public interface UserRepository extends PagingAndSortingRepository<User,Long> {
#Query("from User u where ...")
List<User> findAllUsersWhereFoo(#Param("foo") Foo foo, Pageable pageable);
default List<User> findTop10UsersWhereFoo(Foo foo) {
return findAllUsersWhereFoo(foo, new PageRequest(0,10));
}
}
There is a way you can provide the equivalent of "a setMaxResults(n) by annotation" like in the following:
public interface ISomething extends JpaRepository<XYZ, Long>
{
#Query("FROM XYZ a WHERE a.eventDateTime < :before ORDER BY a.eventDateTime DESC")
List<XYZ> findXYZRecords(#Param("before") Date before, Pageable pageable);
}
This should do the trick, when a pageable is sent as parameter.
For instance to fetch the first 10 records you need to set pageable to this value:
new PageRequest(0, 10)
Use Spring Data Evans (1.7.0 RELEASE)
the new release of Spring Data JPA with another list of modules together called Evans has the feature of using keywords Top20 and First to limit the query result,
so you could now write
List<User> findTop20ByLastname(String lastname, Sort sort);
or
List<User> findTop20ByLastnameOrderByIdDesc(String lastname);
or for a single result
List<User> findFirstByLastnameOrderByIdDesc(String lastname);
Best choice for me is native query:
#Query(value="SELECT * FROM users WHERE other_obj = ?1 LIMIT 1", nativeQuery = true)
User findByOhterObj(OtherObj otherObj);
It's also posible using #QueryHints. Example bellow uses org.eclipse.persistence.config.QueryHints#JDBC_MAX_ROWS
#Query("SELECT u FROM User u WHERE .....")
#QueryHints(#QueryHint(name = JDBC_MAX_ROWS, value = "1"))
Voter findUser();

Related Links

How to extract path variable from responseentity in Junit testing
How to use QueryDslJpaRepository?
How to shorten names of query methods in Spring Data JPA Repositories?
Spring store data in jdbcTemlate(h2 db) permanently
Using the same POJO for a JPA entity and an Elasticsearch document
Does Spring Data MongoDB support enums?
Spring Data-Couchbase Client Configuration with moxi Client Possible?
Is it possible to use one common repository for different entities in Spring data JPA
Unable to inject Mongo Repository into my test class
How to add some custom behavior to Spring Data Jpa generated query?
Spring-Data: Define <mongo:jmx> using java based config
Order By calculated value on 1:n relation in QueryDsl with Spring Data
How to disable the default exposure of Spring Data REST repositories?
How to add links to Spring Data REST projections?
Spring Data: what problems could I have if I replace CrudRepository with JpaRepository?
Spring Data Rest - Multiple endpoints

Categories

HOME
php
spring-data
webview
azure-functions
clearcase
paypal-ipn
concurrency
add-on
gentelella
scheduler
mutation-testing
migrate
phpstorm-2017.1
android-externalstorage
angular4
webstore
mahout-recommender
texas-instruments
async-await
heap-dump
bnf
l20n
playframework-2.0
robolectric
jaspersoft-studio
significance
opam
maven-surefire-plugin
ini
environment
web-push
high-availability
netbios
gsp
gnu-classpath
buildforge
bluemixtools
stackpanel
identify
elastica
extbase
suds
grails3.2.0
vb.net-to-c#
1wire
httphandler
sendinput
apache-toree
destroy
autorelease
comm
word-2016
google-shopping-api
nitrousio
e
system.web.optimization
qpixmap
powerpoint-2013
mathnet
swiffy
persistent-object-store
accessibilityservice
gridbaglayout
taco
ibm-was
ambiguity
algebraixlib
abstract-factory
fuseesb
scala-swing
innerhtml
uno
operands
image-rotation
visual-c++-2012
angular-ui-select
neo4jphp
fileshare
xulrunner
pbkdf2
progress-db
unrealscript
iirf
django-facebook
arel
tfs-sdk
android-authenticator
proc-open
oembed
cmath
icenium
msinfo32
uploading
type-safety
yuidoc
datacontracts
airprint
3270
rtti
gtktextview
version-control-migration
objectinstantiation
activex-exe
regioninfo

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App