MongoRepository Compared two column + Spring Data - spring

I would like to execute the query with compared two column value using mongorepository + spring data (HQL or criteria query). I am showing you relation query and i want to convert to mongo.
Select * from Employee em where em.limit < em.age
I want to convert above query to HQL query using Spring data.

You can use $where to achive this:
db.employee.find( { $where: "this. limit < this. age" } );
check out the document here:
https://docs.mongodb.com/manual/reference/operator/query/where/

Related

Spring JPA - How to create a Pageable with a NativeQuery?

I try to do the following inside a Spring Boot application : create a native query and page it so it can returns a page of a given number of elements from a #RestController.
Here's the snippet of my code, where em is the #PersistanceContext EntityManager, and the repository method is the following, knowing that queryString is the native query :
Query searchQuery = em.createNativeQuery(this.queryString, MyEntity.class);
List<MyEntity> resultsList = searchQuery.getResultList();
return new PageImpl<>(resultsList, PageRequest.of(index,size), resultsList.size());
My problem is that the Page returned has a content of the complete query result, not a content of the size of size parameter inside the PageRequest.of.
Has anybody faced the same issue and could give a working example on how to paginate a nativeQuery please ?
Thanks for your help
You are mixing Spring Data JPA (Pageable) with JPA EntityManager. You can't do that. If you are already using a native query then simply put the pagination in the query. You can use what your database supports, for example the standard:
SELECT [a_bunch_of_columns]
FROM dbo.[some_table]
ORDER BY [some_column_or_columns]
OFFSET #PageSize * (#PageNumber - 1) ROWS
FETCH NEXT #PageSize ROWS ONLY;
this is example of using native query with pagination:
#Query("SELECT c FROM Customer As c INNER JOIN Offer as f on f.id=c.specialOffer.id inner join User As u on u.id=f.user.id where u.id=?1 And c.status=?2")
Page<Customer> getAllCustomerToShop(Integer shopId,String status,Pageable pageable)
and then you can call it as:
getAllCustomerToShop(shopId,"status",PageRequest.of(index, PAGE_SIZE));
Modify your code as follows
Query searchQuery = em.createNativeQuery(this.queryString, MyEntity.class)
.setFirstResult(pageable.getPageNumber() * pageable.getPageSize())
.setMaxResults(pageable.getPageSize());

How to use 'IN' opeartor in Spring boot & Couch base -N1QL query

I have a JSON list from which from which I 'm looking up for a particular value using N1QL query.
It works when I try only if there is only one value in the list.
But if there are multiple values in the list I'm not getting in response.
Json
"suppliers_list": [
"767",
"300767"
]
#Query("SELECT users.*, "
+ "META(users).id as _ID, META(users).cas as _CAS FROM #{#n1ql.bucket}"
+ "users WHERE lower(type)='users' AND ANY usersupplist IN users.suppliers_list SATISFIES usersupplist IN [$1] END")
userRepository.findBySupplierList(String List)
usersDefObjList = userRepository.findBySupplierList("767"); //Working
usersDefObjList = userRepository.findBySupplierList("767,300767"); // Not Working
usersDefObjList = userRepository.findBySupplierList("'767','300767'"); // Not Working
But the same one like works in CouchBase Query window
SELECT users.*,META(users).id as _ID,META(users).cas as _CAS FROM TCI_DATA_MIG users WHERE lower(type)='users' and ANY usersupplist IN users.suppliers_list SATISFIES usersupplist IN ['767','300767'] END
Please let me know your suggestions to get the values in the repository N1QL query to fix this.
In the N1QL right side of IN clause requires ARRAY.
If you know how many elements you can use
usersupplist IN [$1,$2,$3]
If the ARRAY is dynamic and don't know how many elements you can use following and pass in as ARRAY.
usersupplist IN $1
$1 = [ "767", "300767" ] i.e. JsonArray.from("767", "300767")
Check this out Couchbase parameterized N1QL query IN statement

Spring DATA JPA Between and IsBetween keywords

How to get Spring DATA JPA method (like findBy....) for the query below:
Select * from USER where '2016-02-15' between VALID_FROM and VALID_TO;
You should do it in this way
SELECT * FROM users u WHERE e.REFERENCE_FIELD BETWEEN startDate AND endDate
Your code is not very clear, and I dont know what is 2016-02-15, if is the name of your field or is a value, if is a value and you are using between, you must specify a range, and a field to be compared.
EDIT
If you want to use spring data jpa then do it like this
findReferenceFieldBetween(value1,value2);
check the ref. here
In Spring boot: 2.1.6, you can use like below:
List<OrderSummaryEntity> findByCreateTimestampBetween(String fromDate, String toDate);
Just to confirm how it is working internally, If you put spring.jpa.properties.hibernate.show_sql=true property in applocation.properties file, you may see the query like below. Internally nothing but BETWEEN query only.
Hibernate: select order0_.order_id as order_id1_8_,
order0_.create_timestamp as create_t2_8_,
order0_.inventory_at_order as inventor3_8_,
order0_.last_updated_by as last_upd4_8_,
order0_.location_id as location5_8_,
...
...
...
from order_summary order0_
where order0_.create_timestamp between ? and ?
If you want to include both boundary dates in result you can use below in Spring data jpa
#Query(value = "{'field' : {$gte : ?0, $lte : ?1}}", fields="{ 'field' : 1}")
List<DTO> findByFieldBetweenQuery(String first, String second);
Remove fields section if all fields are expected. Hope it helps someone.
SELECT * FROM users WHERE timeStamp BETWEEN 'fromDate' AND 'toDate';
You also can use the below JPA method to get data as the above query.
findByTimeStampGreaterThanEqualAndTimeStampLessThanEqual(fromDate,toDate);

How can we fetch column values which are between two limits in MongoTemplate?

for example i want to find age between 16 and 25 from a collection in mongoDB.
my query is..
Query query = new Query(Criteria.where("visibility").is(1)
.and("type").is("guide").and("age").gte(16).and("age").lte(25));
but it is giving exception. reason is mongo template do not support lte() and gte() with same column. so how can i handle it ? is their any solution ?
Try not to include an extra and("age") part in your criteria. What you need is this:
Query query = new Query(Criteria.where("visibility").is(1)
.and("type").is("guide").and("age").gte(16).lte(25));

Spring Mongo criteria problems with andOperator

I'm trying to create a dynamic mongoDB query using spring Criteria. My query is :
Criteria.where(key1).is(value1).and(key2).is(value2)
The numbers of key/value is not fixed but can change.
I try to use andOperator but it's not for my case.
Can someone help me?
This post explains a similara problem:
Spring Mongo criteria querying twice the same field
This is what you want to do:
Criteria criteria = new Criteria().andOperator(
Criteria.where("key1").is(value1),
Criteria.where("key2").is(value2));
// to print the mongodb query for debug purposes
// System.out.println(criteria.getCriteriaObject());
// execute with a mongoTemplate
List<YourClass> documents = mongoTemplate.find(new Query(criteria), YourClass.class);

Resources