Null and Empty Check for a IN Clause parameter for Spring data jpa #query? - spring

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

Related

Spring data JDBC custom query

I have defined the following custom database query.
#Query("select po.* from purchase_order po where po.purchase_order_number = :purchaseOrderNumber")
List<PurchaseOrder> findByPurchaseOrderNumber(String purchaseOrderNumber);
This query always return null regardless of the value of purchas. On the other hand, if I replace the dynamic parameter purchaseOrderNumber in the query with a hard-coded value (as the one depicted below) it perfectly works.
#Query("select po.* from purchase_order po where po.purchase_order_number = "10")
List<PurchaseOrder> findByPurchaseOrderNumber(String purchaseOrderNumber);
I would appreciate it if someone can help me to understand why my query with the dynamic PurchaseOrderNumber doesn't work?
Specify the name of the query parameter
#Query("select po.* from purchase_order po where po.purchase_order_number = :purchaseOrderNumber")
List<PurchaseOrder> findByPurchaseOrderNumber(#Param("purchaseOrderNumber") String purchaseOrderNumber);

I want to create a search filter in Spring Boot controller, that takes 6 paramas and param value may be null then how to write a Data JPA Query?

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)))

spring data jpa query select all rows if given parameter collection is null

I want to write a query that selects all rows by given type collection for my fileRepository(There are 3 types as "1", "2" and "3"), if that parameter is not given from frontend, then it should return all rows.
I am using a Repository with #RepositoryRestResource annotation to achieve this.
It works fine for single type query(not Collection)
#Query("SELECT t FROM #{#entityName} t WHERE :fileType IS NULL OR t.fileType = :fileType")
Page<MyFile> findByFileType(#Param("fileType") String fileType, #Param("page") Pageable pageable);
it returns all entities when I don't give any arguments i.e : "http://localhost:8080/api/myFiles/search/findByFileType"
and returns all Files which have type "1" when I search with 1 parameter:
"http://localhost:8080/api/myFiles/search/findByFileType?fileType=1"
But problem occurs when I try to write a query from collection of types and I tried this
#Query("SELECT t FROM #{#entityName} t WHERE :fileTypes IS NULL OR t.fileType IN :fileTypes")
Page<MyFile> findByFileType(#Param("fileTypes") Collection<String> fileTypes, #Param("page") Pageable pageable);
It still works for the example localhost links that I gave above but multiple parameter throws "java.sql.SQLSyntaxErrorException: ORA-00920: invalid relational operator" error with this link:
"http://localhost:8080/api/myFiles/search/findByFileType?fileType=1,2"
Edit: I am using Oracle11g as database.

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 to write a query with two ? placeholders in sequence?

I am using a NamedParameterJdbcTemplate, but found that this problem is in the underlying JdbcTemplate class, so I will show the problem as it occurs with the JdbcTemplate (so let's not worry about the safety of the SQL query here).
Here's what I am trying to achieve:
String sql = "SELECT * FROM clients ORDER BY ? ?";
return jdbcTemplate.query(sql,
new Object[] { "name", "ASC" },
new ClientResultSetExtractor());
I expected the first place-holder to be replaced with "name" and the second with "ASC", which would create the valid SQL query:
SELECT * FROM clients ORDER BY name ASC
But unfortunately, running that jdbc query does not work:
ERROR: syntax error at or near "$2" at character 35
STATEMENT: SELECT * FROM clients ORDER BY $1 $2
What am I doing wrong?
EDIT
I had assumed the problem was the two placeholders in sequence, but even when I remove the first one, it still won't accept just the last one, which should tell the query whether to sort in ASC or DESC order. Is this a bug, and if not, why the heck is this not acceptable????
You're trying to use parameters incorrectly.
Parameters are not column names or SQL statement keywords. They're data content (eg., WHERE LastName = ? is a valid parameterized statement, WHERE ? = 'Smith' is not).

Resources