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);
Related
Like I have a page where data are showing like first name, middle name, last name, address, city, state, country, age, salary.
There are a filter implemented that have 4 fields like city, age, salary, state. now I have to made a controller in Spring boot that takes all 4 fields as input params and find data from database using Spring Data JPA.
But my problem is that I want to filter Data sometime by salary only, sometime by city, state, sometime with all 4 params.
So what will be controller code and JPA Repository query to do this filter process.
Please Help me
Thanks in Advance
test if your parameters are null :
"where (:name is null or name = :name) and (:city is null or city = :city)"
I would suggest to use JPA Specification instead,
to know more on specification code here is my thread on stackoverflow
If you want to stick with JPA then here's the query which can help you
where (:field1 is null or table.field1 = :field1)
and (:field2 is null or table.field2 = :field2)
...
...
...
Explanation: The above code will check if the parameter is null, then return true otherwise compare with the column.
You can modify Query with below clause Where you can write query in Repository and in
where clause you can add conditions. So this will work as expected.
#Query(value = "SELECT user from User user WHERE ((:name IS NULL) OR (user.name = :name)) AND ((:city IS NULL) OR (user.city = :city)))
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 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/
My Spring data JPA code to get the data from db based on some search criteria is not working. My DB is SQL Server 2012, same query seem to work with MYSQL DB.
Code Example :
#Query(value = "select * from entity e where e.emp_id=:#{#mySearchCriteria.empId} and ((:#{#mySearchCriteria.deptIds} is null or :#{#mySearchCriteria.deptIds} ='') or e.dept_id in (:#{#mySearchCriteria.deptIds})) ", nativeQuery = true)
public List<Entity> search(#Param("mySearchCriteria") MySearchCriteria mySearchCriteria);
if list mySearchCriteria.deptIds has more than one value- it's not working(it's actually translating it to wrong query. Any lead? Thanks in advance.
Note: data type for deptIds is List of Integer
Its complaining because values of {#mySearchCriteria.deptIds} is comma separated list e.g. 'Value1', 'Value2' so the query gets translated as ('Value1', 'Value2' is null) which causes this error.
Need to verify if list is empty or not and then change the query with IN clause and one without IN clause.
Surround the list by parentheses. This works for me.
(:#{#mySearchCriteria.deptIds}) is null
So there's a method in SpringData findAll(Pageable pageable,Condition condition) ;,
usually I use it like findAll(pageable,myobject) .
The question is when it comes to select some records between some certain field range ,like select out objects whose createDate are between A and B , how to use findAll()?
I tried findAllByCreateDateAfterAndCreateDateBefore(Pageable pageable,Date a,Date b);
But here I can't put myObj as a condtion into the method , and it caused a lot trouble when some fields in the myObj are not sure if it would be used as a condition.
You can simply use JPA Specification to do this, then :
fun findAll(spec: Specification<YourObject>, pageable: Pageable): Page<YourObject>
Here simple example how it should be use :
JPA Specification example