I have a requirement as below.
getting where clause as string from UI, any option to add string in where clause in spring boot to query mongo DB
Eg:(eventType BEGINSWITH 'asdf' AND age > fasdf) AND(age <= 123 OR book NOT ENDSWITH '2344444')
in sql we can add in where clause,but not sure how we can do this in springboot for mongodb
Note: String is dynamic and do not have specific pattern. Parenthesis can be nested. front end angular and service in spring boot
Thanks in advance
using spring data use #Query and pass your find query in value param
like
#Query( "{$and : [{'customUser.id': ?0},{'deleted' : false}],$or:[{'current_location' : true}, {'resident_of' : true}]}")
List findAllByCustomUserA(String userId);
solution for your issue
#Query(value = "{$and : [{'eventType': {$regex:'asdf/',$options:'i'}}, {'age': {$lte : 123}}, {$or[{'book' : {$regex:'/2344444',$options:'i'}}]} ]}")
for more details visit how to make mongo query
https://docs.mongodb.com/manual/reference/operator/query/regex/
Related
Hi I use spring jpa to access my data in my spring boot project.I am wondering that is there any difference between #Query annatotation and critearia api in jpa.Are they totaly same or is there any difference(Their writing styles are different ,and I mean any performance or other issue between them)
Mostly I prefer #Query annotation it looks simple.Or any other option some one can advice like #Query or criteria api in spring jpa.And is there any disadvantages of #Query style?
#Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
List<Book> findBooksByAuthorNameAndTitle(String authorName, String title) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> cq = cb.createQuery(Book.class);
Using #Query we can pass static query or pre compiled query so we can perform both select and non-select operations on the data
where as Criteria is suitable for executing Dynamic Queries such requirements occurs when data are know at run time
but using criteria api we can only perform select operations on the data.
For example
#Query(value = "SELECT u FROM User u")
List<User> findAllUsers(Sort sort);
We can also work with pre compiled query using #Query
For Example
#Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(
#Param("status") Integer status,
#Param("name") String name);)
Dynamic queries like
Criteria cr = session.createCriteria(Employee.class);
// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));
// To get records having salary less than 2000
cr.add(Restrictions.lt("salary", 2000));
Actual use of Dynamic queries comes when we'll encounter the need for building SQL statements based on conditions or data sets whose values are only known at runtime. And, in those cases, we can't just use a static query So we can't just use the #Query annotation since we can't provide a static SQL statement.In such case we use Criteria API
For more info follow the link provided
#Query and Criteria
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());
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/
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);
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);