Spring data JDBC custom query - spring

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

Related

Getting Second Order SQL Injection in Spring Hibernate

I am facing Second Order SQL Injection in the Spring-Hibernate application after scanning through the Checkmarx tool, I have gone through multiple questions in StackOverflow and in other platforms as well but did not get the right finding.
could you please look into the below code snip,
public String getOrderId(order_name){
String returnId= null;
Query query = entityManager.createNativeQuery("select order_id from order where order_name=?");
List<String> dataset = query.setParameter(1,order_name).getResultList();
if(dataset!=null){
returnId = dataset. Get(0);
}
return returnId;
}
In this above method, while calling getResultList(), getting a high vulnerability issue that, this method returns data flows through the code without being properly sanitized or validated, and eventually used in further database query in the method.
Earlier code was like this,
public String getOrderId(order_name){
String returnId= null;
String q = "select order_id from order where order_name="+order_name;
Query query = entityManager.createNativeQuery(q);
and directly it was used as a string append in query, which I have modified with set parameter,
Query query = entityManager.createNativeQuery("select order_id from order where order_name=?");
List<String> dataset = query.setParameter(1,order_name).getResultList();
but still after getting data from query.getResultSet(), it is asking for sanitizing and validating the data before use in further database query method.
and this return data is being used in further query like select * from return_Data where clause. (properly used in where clause to set parameter to avoid SQL injection).
and in the above query is used in another method where we pass return_Data as input to it.
could you please help here to know what checks and validation can be added to overcome this type of issue. Thanks in advance for prompt response.

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

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

How can I place a n1ql query with variables in a spring #Query annotation?

I have the following N1QL query:
UPDATE `bucket`
SET b.terms.min_due.`value` = "12345" FOR b IN balances END
WHERE entry_id = "12345"
I want to place it in an #Query annotated repository method, but the values for value and entry_id need to be variable.
They are for a patch operation that updates only parts of the document. I have to do it using inline N1ql via #Query, so it is the only thing I've tried.
#Query(UPDATE `bucket` SET b.terms.min_due.`value` = "12345" FOR b IN balances END WHERE entry_id = "12345")
<T> Mono<T> patch(T Aggregate);
I want to construct a repository method that replaces "12345" for value and entry_id with values pulled from the aggregate, then executes the N1ql query, updating only the value specified in the statement instead of the whole couchbase document.
You can use the standard spEL syntax for that:
#Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and companyId = $2 and $1 within #{#n1ql.bucket}")
BusinessUnity findByAreaRefId(String areaRefId, String companyId);

How to query a field in a related object in a ParseQuery

I'm using Parse.com and I am running a query that obtains objects in a many-to-many relational table (call this table 'RelationTable'). Obviously this table has links to objects in another table (let's call this SubObject). Now, from this query, I need to filter results by searching on a field contained within the SubObject (call this SearchField).
Any ideas on how to do this? I already have the includeKey and am trying the '.' operator in SQL to access a field in the subclass, but it's not working. Below is the code I have so far:
ParseQuery<ParseObject> query = ParseQuery.getQuery("RelationTable);
query.include("subObject"); //subObject is field name where SubObject is stored. Note CAPS difference
query.whereContains("SubObject.SearchField", searchString);
You can create a subquery on the user object, and use whereMatchesQuery on your RelationTable query :
ParseQuery<ParseObject> query = ParseQuery.getQuery("RelationTable);
query.include("subObject");
ParseQuery<ParseObject> innerQuery = ParseQuery.getQuery("SubObject");
innerQuery.whereContains("SearchField", searchString);
query.whereMatchesQuery("subObject", innerQuery);

SimpleJpaRepository Count Query

I've modified an existing RESTful/JDBC application i have to work with new features in Spring 4... specifically the JpaRepository. It will:
1) Retrieve a list of transactions for a specified date. This works fine
2) Retrieve a count of transactions by type for a specified date. This is not working as expected.
The queries are setup similarly, but the actual return types are very different.
I have POJOs for each query
My transactions JPA respository looks like:
public interface MyTransactionsRepository extends JpaRepository<MyTransactions, Long>
//My query works like a charm.
#Query( value = "SELECT * from ACTIVITI_TMP.BATCH_TABLE WHERE TO_CHAR(last_action, 'YYYY-MM-DD') = ?1", nativeQuery = true )
List< MyTransactions > findAllBy_ToChar_LastAction( String lastActionDateString );
This returns a list of MyTransactions objects as expected. Debugging, i see the returned object as ArrayList. Looking inside the elementData, I see that each object is, as expected, a MyTransactions object.
My second repository/query is where i'm having troubles.
public interface MyCountsRepository extends JpaRepository<MyCounts, Long>
#Query( value = "SELECT send_method, COUNT(*) AS counter FROM ACTIVITI_TMP.BATCH_TABLE WHERE TO_CHAR(last_action, 'YYYY-MM-DD') = ?1 GROUP BY send_method ORDER BY send_method", nativeQuery = true )
List<MyCounts> countBy_ToChar_LastAction( String lastActionDateString );
This DOES NOT return List as expected.
The object that holds the returned data was originally defined as List, but when I inspect this object in Eclipse, I see instead that it is holding an ArrayList. Drilling down to the elementData, each object is actually an Object[2]... NOT a MyCounts object.
I've modified the MyCountsRepository query as follows
ArrayList<Object[]> countBy_ToChar_LastAction( String lastActionDateString );
Then, inside my controller class, I create a MyCounts object for each element in List and then return List
This works, but... I don't understand why i have to go thru all this?
I can query a view as easily as a table.
Why doesn't JPA/Hibernate treat this as a simple 2 column table? send_method varchar(x) and count (int or long)
I know there are issues or nuances for how JPA treats queries with counts in them, but i've not seen anything like this referenced.
Many thanks for any help you can provide in clarifying this issue.
Anthony
That is the expected behaviour when you're doing a "group by". It will not map to a specific entity. Only way this might work is if you had a view in your database that summarized the data by send_method and you could map an entity to it.

Resources