How to write dynamic native queries in cosmos DB - java

I have a situation where i have couple of fields i have to pass while calling the cosmos DB , but those fields may not always have values. Some of them might be null while passing them to the repository method. I am trying to do it like below
public interface CachedRepository{
#Query(value="select * from abc a where (#base=null or a.base=#base) and (#position=null or a.position=#position) and (#active=null or a.active = #active)")
List<BackList> getBackListOptions(#Param("base")String base,#Param("position")String position,#Param("active") String active);
The implementation class
latestDetails = repositoryA.getBackListOptions(p.getBase(),p.getPosition(),p.getActive().get(0));//active is a List and we are passing one value
I am trying to pass the request without the active parameter(i.e. active is null in the request) The exception i am getting is
Can not invoke "java.util.List.get(int)" because the return value of request.Pick.getActive() is null
The cosmos Table is
{
'_id":"a25777-j"
"empId": 2436,
"base":"JH",
"position":"HG",
"active":"J"
.........
}
And i am taking reference from this answer
How to write dynamic sql in Spring Data Azure Cosmos DB
Please let me know where i am doing it wrong

The code you have given should work fine if either null or an actual value is passed for any of the parameters. But in your case, for active, it is neither. Nothing is passed, not even null.
It seems from the comments in your code that "active" is an object of type List, and you are attempting to pass a value in that list to getBackListOptions, and extracting that value directly in the method call with p.getActive().get(0). But I think your implementation code is failing where p.getActive().get(0) is called, before getBackListOptions is even invoked. The error you are getting is not something that is returned from Cosmos Spring client, which I believe is doing what it should. You need to handle the values you are passing properly before passing them. I think you could handle this something like below.
String base = p.getBase(); //set the value here so it is clear where failure is
String position = p.getPosition(); //set the value here so it is clear where failure is
String active = p.getActive() == null ? null : p.getActive().get(0); //I think this line was failing before because p.getActive() was null, but this condition handles that case
latestDetails = repositoryA.getBackListOptions(base,position,active);//active is a List and we are passing one value

Related

Morphia update document with undefined number of fields

I'm working on a small project using morphia for MongoDB. I want to know what is the best way to update a document without knowing first hand what field to update. Say for example, I have a form, after having saved to database I might want to come back and change some fields but I haven't decided yet what to change.
My current solution is doing an update for all fields whether it is changed or not and of course it throws null exception. Morphia complains on null value update.
My code looks like this:
Query<Project> q = datastore.find(Project.class, "_id", projectToUpdate.getId());
UpdateOperations<Project> update
= datastore.createUpdateOperations(Project.class)
.set("name", updatedProject.getName())
.set("deadline", updatedProject.getDeadline())
.set("priority", updatedProject.getPriority())
.set("completion", updatedProject.getCompletion())
.set("description", updatedProject.getDescription())
.set("projectManager", updatedProject.getPM())
.set("collaborators", updatedProject.getAllCollaborators())
.set("teams", updatedProject.getAllTeams())
.set("userStories", updatedProject.getUserStories())
.set("log", updatedProject.getLog());
datastore.findAndModify(q, update);
Exception
Exception in thread "main" org.mongodb.morphia.query.QueryException: Value cannot be null.
at org.mongodb.morphia.query.UpdateOpsImpl.set(UpdateOpsImpl.java:220)
at controllers.QueryProjects.updateProject(QueryProjects.java:78)
at controllers.DBConnection.TestMongo(DBConnection.java:152)
at penelope.Main.main(Main.java:12)
I was thinking about using delegate/event handler to update each field individually but I'm afraid that might degrade the performance.
You should just use datastore.save(). See an example at http://mongodb.github.io/morphia/1.3/getting-started/quick-tour/

How to pass null to SQL parameter in java?

I have a scenario where in i have to pass null to a SQL parameter through java but i am getting SQLGrammarException. If i am passing some value it works fine. Please guide if i am wrong somewhere.
Below is my code:
StringBuffer query;
query = new StringBuffer(
"SELECT * "+
"FROM table(package.func(travel_type => travel_search_type("+
"travel_place_no => :travelPlaceNo"+
")))" );
Query query1 = em.createNativeQuery(query.toString());
query1.setParameter("travelPlaceNo",null);
searchresults = query1.getResultList();
Exception:
org.hibernate.exception.SQLGrammarException
This is what i do through SQL Developer and it works fine:
SELECT *
FROM table(package.func(travel_type => travel_search_type(
travel_place_no => NULL))) ;
Please guide.
While calling the 2 argument signatures of the method, null is not an allowed value. You can use, instead, the 3 argument signature setParameter(String name,
Object val,
Type type) specifying the data type and it should work.
EDIT:
Ok, I see there is also another problem: even if the replacemente worked, what you are trying to execute is a >= NULL. In this case, I'm afraid that you are going to have to handle mannually the StringBuffer creation. Maybe just force an always false condition without parameters if its null, like `1!=2', and otherwise just handle it as you are doing on your sql example (write mannually 'NULL' instead of the parameter placeholder).

SharedPreferences getString NULL parameter

Will I receive an error (Exception) on some devices if I set the second parameter of SharedPreferences.getString NULL?
SharedPreferences settings = ...
String data = settings.getString(_.PREFIX , null);
Will it cause an exception or an error on at least one device? Or I have to wrap this part of code in try-catch block?
If you are asking if you will get an exception if you set the second parameter to null, the answer is no (at least not unless you reference the result without first checking it is not null). The second parameter in the getString() method is the default value (i.e. the value that will be returned if there is nothing found for your prefix. So, it is perfectly acceptable to set null as your default value, as long as you realize (and account for) the fact that the value returned by your getString() could be null.
String data = settings.getString(_.PREFIX , null/Null here is default value/);
null - u can receive when your SraredPreferences have not this item(For example if u call/get this string before setting to this field any info or user clear cash of application from settings of device). I think it's can be normal situation, and u can remove "null" with some default value if you hope to got it(some emum field).
If u don't suppose get null validate data before using.
I thin'k your app must be ready get both variant, because user can change normal workflow.

Unable to retrive Projection/Multi- Relantion field Requests.Custom_SFDCChangeReqID2 using versionone java sdk

I have been trying to retrieve information from querying a specific Asset(Story/Defect) on V1 using the VersionOne.SDK.Java.APIClient. I have been able to retrieve information like ID.Number, Status.Name but not Requests.Custom_SFDCChangeReqID2 under a Story or a Defect.
I check the metadata for:
https://.../Story?xsl=api.xsl
https://.../meta.V1/Defect?xsl=api.xsl
https://.../meta.V1/Request?xsl=api.xsl
And the naming and information looks right.
Here is my code:
IAssetType type = metaModel.getAssetType("Story");
IAttributeDefinition requestCRIDAttribute = type.getAttributeDefinition("Requests.Custom_SFDCChangeReqID2");
IAttributeDefinition idNumberAttribute = type.getAttributeDefinition("ID.Number")
Query query = new Query(type);
query.getSelection().add(requestCRIDAttribute);
query.getSelection().add(idNumberAttribute);
Asset[] results = v1Api.retrieve(query).getAssets();
String RequestCRID= result.getAttribute(requestCRIDAttribute).getValue().toString();
String IdNumber= result.getAttribute(idNumberAttribute).getValue().toString();
At this point, I can get some values for ID.Number but I am not able to retrieving any information for the value Custom_SFDCChangeReqID2.
When I run the restful query to retrieve information using a browser from a server standpoint it works and it does retrieve the information I am looking for. I used this syntax:
https://.../rest-1.v1/Data/Story?sel=Number,ID,Story.Requests.Custom_SFDCChangeReqID2,Story.
Alex: Remember that Results is an array of Asset´s, so I guess you should be accessing the information using something like
String RequestCRID= results[0].getAttribute(requestCRIDAttribute).getValue().toString();
String IdNumber= results[0].getAttribute(idNumberAttribute).getValue().toString();
or Iterate through the array.
Also notice that you have defined:
Asset[] results and not result
Hi thanks for your answer! I completely forgot about representing the loop, I was too focus on the retriving information part, yes I was actually using a loop and yes I created a temporary variable to check what I was getting from the query in the form
Because I was getting the variables one by one so I was only using the first record. My code works after all. It was just that What I was querying didn't contain any information of my use, that's why I was not finding any. Anyway thanks for your comment and observations

Spring JDBC Template check for Null results

I am bit new to Spring and Spring JDBC Template. I am retrieving some rows from my database using mysql. The query will produce null results in some times. Therefore I need to do a null check for the results retrieved using JDBC Template.
This is my code for retrieving data from database.
try {
String sqlArrears = "SELECT SUM(total_payable) FROM letter_delaypayments WHERE status = '1' AND customer_order_id = '"+customerOrderIdList.get(j)+"' AND year(row_added_date) = year(curdate()) AND month(row_added_date) = month(curdate())";
double arrearsAmountForSingleCustomer = getSimpleJdbcTemplate().queryForObject(sqlArrears, Double.class);
} catch (Exception e) {
System.out.println("EXCEPTION: While taking relavant arrears payments for customer order ids : "+e);
}
There may not be rows in the database table in some cases. In those cases, this query pass Null pointer exception.
So what I need to know is, can I check for the NULL value it returns and put an exception in that cases or else, Do I have to look for the row count particular query matches with and then do the retrieval.
I.E - look for the row count particular query matches,
if it is 0, add an exception.
If it is >1, retrieve the results using above query.
What should I do here?
Could you please let me know, whether there is a way to check for the null result at the same time query retrieves the results.
Thank you!
I would suggest that such logic belongs in the service layer. Your DAO can return a Double (not double) and you can check for null in the service layer.

Categories

Resources