Using the latest Spring Data Mongo (2.1.1 at time of writing), how do I specify to get the first record of a "custom" query method? Here is an example:
#Query(value="{name: ?0, approval: {'$ne': null}}",
sort="{'approval.approvedDate': -1}",
fields = "{ _id: 1 }")
List<Item> getLatestApprovedIdByName(String name, Pageable pageable);
/**
* Finds the id of the most recently approved document with the given name.
*/
default Item getLatestApprovedIdByName(String name) {
return getLatestApprovedIdByName(name, PageRequest.of(0, 1)).stream()
.findFirst()
.orElse(null);
}
Ideally I could just annotate getLatestApprvedIdByName taking only the String parameter.
There doesn't seem to be a limit field on the org.springframework.data.mongodb.repository.Query annotation.
It seems odd because I can emulate everything the named methods do except findFirst.
Without the Pageable, I get IncorrectResultSizeDataAccessException, and returning a List is not acceptable because I don't want to waste time returning an arbitrarily large result, plus the complicated code needing to deal with the possibility of 0 or 1 items.
Because your query returns multiple documents, there's no way to make it return a single Item directly.
Using Stream
// Repository
#Query(value="{name: ?0, approval: {'$ne': null}}",
sort="{'approval.approvedDate': -1}",
fields = "{ _id: 1 }")
Stream<Item> getLatestApprovedIdByName(String name);
// Service
default Item getLatestApprovedIdByName(String name) {
return getLatestApprovedIdByName(name).stream().findFirst().orElse(null);
}
Due to the way Stream works, you'll only fetch the first query result instead of the entire result set. For more information, please see the documentation.
Using Page and Pageable
// Repository
#Query(value = "{name: ?0, approval: {'$ne': null}}", fields = "{ _id: 1 }")
Page<Item> getLatestApprovedIdByName(String name, Pageable pageable);
// Service
default Item getLatestApprovedIdByName(String name) {
PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "approval.approvedDate"));
return getLatestApprovedIdByName(name, request).getContent().get(0);
}
By making use of PageRequest, you can specify how many results you want as well as specify the sort order. Based on this answer.
Related
I have a Couchbase-Document "Group" with a list of group-members-names. I want to query for all groups of one person. I managed to do it with N1QL ARRAY_CONTAINS - see in code example - but i hoped that i could generate the query from the method name as it is usual in Spring Data.
Any help is appreciated :)
I tried
public List<MyGroup> findAllByMembers(String member); and public List<MyGroup> findByMembers(String member); but they just return an empty list - i guess they try to match the whole "members" value and don't recognize it as a list -, no errors.
Code
My Document with a List field
#Data
#Document
public class MyGroup {
private String name;
private List<String> members = new ArrayList<>();
}
My Repository
#RepositoryDefinition(domainClass = MyGroup.class, idClass = String.class)
public interface MyGroupRepository extends CouchbaseRepository<MyGroup, String> {
//#Query("#{#n1ql.selectEntity} WHERE ARRAY_CONTAINS(members,$1) AND #{#n1ql.filter}")
public List<MyGroup> findAllByMembers(String member);
}
Expected
Given a "group1" with "member1" in members.
repository.findAllByMembers("member1"); should return ["group1"].
Couchbase is limited by the Spring Data specification. Unfortunately, we can't simply add new behaviors to it (if you switch to a relational database, it has to work with no breaking points). So, whenever you need to query something that has a N1QL specific function/keyword, you have to write a query via #Query
I'm creating a RESTful API. I need to to be able to send a number to the API specifying the amount of news items it needs to return.
I already looked for some things and according to the documentation it is possible to limit your results, but I can't find anything about how to make it variable. So my question is: Is this even possible to do or do I need to write my own custom query for this.
I already tried things like:
Iterable<NewsItem> findTopAmountByOrderByDatetimeDesc(Integer amount); where Amount would be filled in by the given Integer "amount", but maybe it is stupid to even think this would be possible although it would be a nice feature in my opinion.
What I have now (not variable, so it doesn't care about the given number):
NewsItemApi:
#RequestMapping(value = "/newsitems/amount",
produces = { "application/json" },
method = RequestMethod.GET)
NewsItemRepository:
Iterable<NewsItem> findTop2ByOrderByDatetimeDesc();
NewsItemApiController:
public ResponseEntity<Iterable> getLastNewsItems(#NotNull #ApiParam(value = "amount of news items to return", required = true) #Valid #RequestParam(value = "amount", required = true) Integer amount) {
return ResponseEntity.accepted().body(this.newsItemRepository.findTop2ByOrderByDatetimeDesc());
}
You can create repository and use #Query annotation to make custom requests, something like this:
public interface NewsRepository extends JpaRepository<News, Long> {
#Query(value = "SELECT * FROM NEWS ODER BY FIELD_YOU_WANT_TO_ODER_BY DESC LIMIT ?1", nativeQuery = true)
List<News> getLatestNews(Integer amount);
}
You would have to use #Query, something like:
#Query("select n from NewsItem n order by n.datetime desc limit :num", nativeQuery = true)
Iterable<NewsItem> findTopXByOrderByDatetimeDesc(#Param("num") int num);
Of course use limit keyword according to your database.
I am using spring-sata-mongodb 1.8.2 with MongoRepository and I am trying to use the mongo $slice option to limit a list size when query, but I can't find this option in the mongorepository.
my classes look like this:
public class InnerField{
public String a;
public String b;
public int n;
}
#Document(collection="Record")
punlic class Record{
public ObjectId id;
public List<InnerField> fields;
public int numer;
}
As you can see I have one collection name "Record" and the document contains the InnerField. the InnerField list is growing all the time so i want to limit the number of the selected fields when I am querying.
I saw that: https://docs.mongodb.org/v3.0/tutorial/project-fields-from-query-results/
which is exactly what I need but I couldn't find the relevant reference in mongorepository.
Any ideas?
Providing an abstraction for the $slice operator in Query is still an open issue. Please vote for DATAMONGO-1230 and help us prioritize.
For now you still can fall back to using BasicQuery.
String qry = "{ \"_id\" : \"record-id\"}";
String fields = "{\"fields\": { \"$slice\": 2} }";
BasicQuery query = new BasicQuery(qry, fields);
Use slice functionality as provided in Java Mongo driver using projection as in below code.
For Example:
List<Entity> list = new ArrayList<Entity>();
// Return the last 10 weeks data only
FindIterable<Document> list = db.getDBCollection("COLLECTION").find()
.projection(Projections.fields(Projections.slice("count", -10)));
MongoCursor<Document> doc = list.iterator();
while(doc.hasNext()){
list.add(new Gson().fromJson(doc.next().toJson(), Entity.class));
}
The above query will fetch all documents of type Entity class and the "field" list of each Entity class document will have only last 10 records.
I found in unit test file (DATAMONGO-1457) way to use slice. Some thing like this.
newAggregation(
UserWithLikes.class,
match(new Criteria()),
project().and("likes").slice(2)
);
I have had the misfortune of working in Java for some time, coming from the .net world. Ranting aside, I am simply looking to implement a Repository that can handle use of predicates and must have pagination. I am unable to find a good way to do this.
// IContactRepository.java
public interface IContactRepository extends Repository<Contact,Long> {
}
// Application.java
contactRepo.findAll(predicate, new PageRequest(0,10));
I want to to be able to find contacts with contact name containing search term or contact phone number containing search term and then get first 10 matches.
In the .net world, if I was not using an orm I would use sql server's awesome TSQL to get what I want but stuck with Oracle here. I would otherwise use some ORM and pass a lambda to the query function as predicate.
In my configuration I am also using JPA and spring. (FOR STATIC PREDICATES. If you want to add predicates(search terms) dynamically please let me know.)
// IContactRepository.java
public interface IContactRepository extends CrudRepository<Contact,Long>, PagingAndSortingRepository<Contact, Long> {
List<Contact> findByContactNameLikeAndContactPhoneLike(String name, String phone, Pageable pageable)
}
I tried Pageable with CrudRepo and it works fine.
And for the lambda you are right :)
In my configuration your implementation looks like this :
IContactRepository contactRepo = context.getBean(IContactRepository.class);
List<Contacts> results = contactRepo.findByContactNameLikeAndContactPhoneLike("%CA%","%090%" , new PageRequest(1, 20));
http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html
Please have a look Query creation under 1.2.2 Defining query methods
I am guessing you are looking at Predicate because you want to be able to execute any arbitrarily complex query.
However there is no findAll(Predicate, Pageable) method.
I suggest that you check out Specification and JpaSpecificationExecutor. Your code would look like this:
public interface IContactRepository extends JpaRepository<Contact,Long>, JpaSpecificationExecutor<Contact> {
}
Then you would have access to the method findAll(Specification, Pageable). And as per your requirement, Specification is a Functional Interface, so you can use a lambda to easily pass in an implementation.
Check out section 2.5 from the documentation for more details.
Here is the Javadoc of Specification and here is the Javadoc of JpaSpecificationExecutor
Also if you have to endure the pain of Java, you should probably drop the I in IContactRepository :). Java code usually forgoes that .NET practice
Thats my implementation maybe help to you:
#Override
public Page<Advert> findActiveAdverts(String searchValue, String availability, Long branchId, Long categoryId, Pageable pageable) {
Page<Advert> adverts = advertRepository.findAll(new Specification<Advert>() {
#Override
public javax.persistence.criteria.Predicate toPredicate(Root<Advert> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(root.get(Advert_.ACTIVE), true));
if (!StringUtils.isEmpty(searchValue)) {
predicates.add(cb.or(
cb.like(root.get(Advert_.TITLE), "%" + searchValue + "%"),
cb.like(root.get(Advert_.EXPLANATION), "%" + searchValue + "%"))
);
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
}, pageable);
return adverts;
}
I am trying to incorporate Spring-Data-JPA into my project.
One thing that confuses me is how do I 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 findByOtherObj(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 is such an important feature not built into Spring-Data?
If I implement this feature manually:
public class UserRepositoryImpl implements UserRepository
I have to implement tons of predefined methods in CrudRepository, this would 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 this:
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);
new PageRequest(0,10) doesn't work in newer Spring versions (I am using 2.2.1.RELEASE). Basically, the constructor got an additional parameter as Sort type. Moreover, the constructor is protected so you have to either use one of its child classes or call its of static method:
PageRequest.of(0, 10, Sort.sort(User.class).by(User::getFirstName).ascending()))
You can also omit the use of Sort parameter and implicitly user the default sort (sort by pk, etc.):
PageRequest.of(0, 10)
Your function declaration should be something like this:
List<User> findByUsername(String username, Pageable pageable)
and the function will be:
userRepository.findByUsername("Abbas", PageRequest.of(0,10, Sort.sort(User.class).by(User::getLastName).ascending());
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();
If your class #Repository extends JpaRepository you can use the example below.
int limited = 100;
Pageable pageable = new PageRequest(0,limited);
Page<Transaction> transactionsPage = transactionRepository.findAll(specification, pageable);
return transactionsPage.getContent();
getContent return a List<Transaction>.
Use
Pageable pageable = PageRequest.of(0,1);
Page<Transaction> transactionsPage = transactionRepository.findAll(specification, pageable);
return transactionsPage.getContent();