Create nested reponse from sql view with spring boot DTO - mysql

I have a view generated form multiple tables, I want to return a nested response from the view like the following.
[
{
"id":"c2bb81dd-6837-4dd7-b903-4c2ec938f78a",
"name":"Olive Oil",
"date":"2023-01-05",
"quantity":180,
"consumption":50,
"demand":0.00,
"max":100.00,
"safety":20.00,
"unit":"L",
"consumedProducts":[
{
"id":"197f88e6-b941-414d-b571-8be6a64ce82f",
"name":"Burger",
},
{
"id":"0010f6d6-71d3-4553-aaf5-96383b3c0c28",
"name":"Sandwich",
}
],
"wastage":{
"preparation":15.25,
"expiration":1
}
}
]
I want to write hibernate query with projection to return this response
The view data.
enter image description here
I tried the following query but it didn't get the right response
select new com.intelmatix.demo.service.dto.IngredientViewDTO( iview.id as id,\n"
+ "iview.name as name,\n"
+ "iview.date as date,\n"
+ "iview.quantity as quantity,\n"
+ "iview.consumption as consumption,\n"
+ "iview.demand as demand,\n"
+ "iview.max as max,\n"
+ "iview.safety as safety,\n"
+ "iview.type as type,\n"
+ "iview.pid as pid,\n"
+ "iview.productname as productname)\n"
+ "from IngredientView iview\n"
+ "group by
iview.id,iview.date,iview.quantity,iview.consumption,iview.demand,iview.type,iview.pid, iview.wastage \n

Related

How to query mongo db with a nested model?

I have data similar to the below in my mongodb table called Resources.
{
"_id":"testuser",
"_class":"com.Resources",
"allocations":[
{
"contractId":"5083",
"status":"UNKNOWN"
}
]
}
{
"_id":"testuser",
"_class":"com.Resources",
"allocations":[
{
"contractId":"5084",
"status":"Dead"
}
]
}
{
"_id":"testuser2",
"_class":"com.Resources",
"allocations":[
{
"contractId":"5085",
"status":"Live"
}
]
}
I would like to run a query in a shell that returns all contractIDs and its status for each _id, which is my resourceID effectively in the table. The format should be "_id - contractId - status". For example when run with the above data, we should see the below:
testuser - 5083 - UNKNOWN
testuser - 5084 - Dead
testuser2 - 5085 - Live
Any help is appreciated.
Try this
db.getCollection('Collection').find(/*Some Query*/).forEach(function(data){
data.allocations.forEach(function(result){
print(data._id + '-' + result.contractId + '-' + result.status);
})
})

Mule ESB : Traverse a json payload and make where clause condition for Salesforce

Following is the input in terms of json payload and what is required is to form a where clause statement which I can use for salesforce query.
Note: The number of query fields can vary from 1 to n.
Input payload
{
"object_type": "contact",
"query_fields": [
{
"field_name": "CreatedById", "field_value": "005g0000003qelYAAQ"},
{
"field_name": "BillingState", "field_value": "KA"}
]
}
Sample output:
#[json:query_fields[0]/field_name] = '#[json:query_fields[0]/field_value]' AND #[json:query_fields[0]/field_name] = '#[json:query_fields[0]/field_value]'
I figured out the solution to this problem and thought of sharing the same with us all.
Step 1: Transformed the above mentioned input payload into array:
<dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
payload map {
field_name : $.field_name,
field_value : $.field_value
}]]></dw:set-payload>
Step 2: Used an expression component to traverse the array and take the value of it so that I can use the values to form a where clause for the Salesforce query further in my flow.
<![CDATA[String wrcls ="";
int m=1;
int n=0;
for (String counter : flowVars.queryfields)
{
wrcls += payload[m].field_name[n] + " = " + "'" + payload[m].field_value[n] + "'" + " AND "
m = m + 1;
n = n + 1;
}
payload = wrcls;
payload = payload.replaceAll(" AND $", "");]]>

Using the CouchDB(1.6.1) List function to output to a csv file

I am trying to master the principles/syntax of using a list function in CouchDB 1.6.1 to output specific fields to a csv file.
I have set up a simple output to html and this seems easier to do and it works well.
What I want to do is have a view, which the list function requires, to output selected fields from the database and output the data to a csv file.
What I can't seem to be able to do is get the list function to 'read' the specific fields from the view output, which I succeded in doing to obtain html output.
The view function looks something like this:
function(doc){
emit({'A':doc.a, 'B':doc.b, 'C':doc.c.d .....}, null);}
The html list function would look something like this:
"function(head, req){
start({'headers': {
'Content-Type': 'text/html' }});
send('<html><body><table>');
send('<tr><th>A</th><th>B</th><th>C</th></tr>');
while(row=getRow()){
send(''.concat( '<tr>', '<td>' + toJSON(row.key.A) + '</td>','<td>' + toJSON(row.key.B) + '</td>','<td>' + toJSON(row.key.C) + '</td>', '</tr>' ));}
send('</table></body></html>');}"
A similar list function for csv output for the same view should look like:
"function(head, req){
start({'headers': { 'Content-Type': 'text/csv' }});
send('A' +','+ 'B' +','+'C' + '\\n');
while(row=getRow()){
send(''.concat( toJSON(row.key.A) , toJSON(row.key.B) , toJSON(row.key.C) ));};}"
this results in " "error":"compilation_error","reason":"Expression does not eval to a function ...."
I have tried numerous variations of the csv function without success except for a jumbled lot of incorrectly formatted text.
A recommended starting point for a csv list function was, on a certain website, given as:
function (head, req) {
start({
“headers”: {
“Content-Type”: “text/csv”
}
});
send(‘Username, Name, Email\n’);
while(row = getRow()) {
send(row.value.username+’,’+row.value.email+’,’+row.value.metadata.name+’\n’);
}
}
I cannot get this structure to work at all.
I would appreciate some input on the correct syntax to use please.
I was able to find a guideline here. A slideshare by Oliver Kurowski.
The basic principles are:
"views": {
"byPrice": {
"map": "function(doc){emit(doc.price, [doc.make,doc.year]);};"
}
}
"lists": {
"csv": "function(head,req){start({'headers':{'Content-Type':'text/csv'}});send('Make'+','+'Year'+','+'Price'+'\\n');while(row=getRow()){send(row.value+','+row.key+'\\n');}};"
}
It worked fine.
Thank you Oliver.

is it possible to have a for loop in JSRender with incremental variable i?

i have template (an html file) with is getting renders with JSON data using JSRender.
My Sample Template is as follows
<ul id="membersList">
{{for UserConnection}}
<li>
<div>
<a title="{{:Fullname}}">
<br />
<img src="sample.png"/><br />
{{:Fullname}}</a>
</div>
</li>
{{/for}}
My Json data is
[
{
"ApplicationName": "appone",
"Title": "Title one",
" UserConnection ": [
{
"Id": 210,
" email ": " abc1#xyz.com ",
},
{
"Id": 0,
" email ": " ",
},
{
"Id": 211,
" email ": " abc2#xyz.com ",
}
]
}
];
Now my requirement is the i should hide of div if in particular the 2nd item of
the JSON has the its id value as 0.
Is it possibel in JSRender to check some thing which we do in c# like
for (i = 0 ; i < 10 ; i++)
{
if (userConnection[i] = 0)
// show the div
else
// dont show
}
i.e. if i can access UserConnection[i] even in JSRender, then i can show or hide the div.
Is it possible?
You can look at this example to see how to get to the parent data https://www.jsviews.com/#parentdata
and there is #index while in the for loop to get access to the current index.
I think really the answer to your question is to use a helper to construct the div with either display on or off at the time it is created.
A helper, converter, and customer tags are all general javascript functions that you register and then use.

Json Data not populating jqGrid

My jqGrid is not populating on-submitting my form in Asp.net MVC 4 ... I am want to find out why... I have an ajax method that returns this Json string and it is a Json string in the Network response browser...
"{\"total\":1,\"page\":1,\"records\":1,\"rows\":[{\"cell\":[\"\",\"342352857634\",\"test\",\"test\",\"5/8/2012 11:39:38 AM\",\"1\",\"\",\"1/1/0001 12:00:00 AM\",\"1/1/0001 12:00:00 AM\",\"1/1/0001 12:00:00 AM\"]}]}"
this is the function that does all of the Magic.
$('#SearchPatID').submit(function (event) {
//alert("What the motherFuck is going on here!");
debugger;
var theURL = this.action;
var type = this.methd;
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
debugger;
bindData(result);
}
});
return false;
});
var bindData = function (result) {
debugger;
alert('Glad this is kind-of working!');
$("#list").setGridParam({
datatype: 'jsonstring',
datastr: result,
caption: 'Suck It!'
}).trigger("reloadGrid");
}
UPDATE... I chamged my bindData function to Just setGridParam. and reload... Still doesn't work, but I think I am on the right path finally... More updates below...
What Am I missing? I have my Json data, everything should be working out fine right?
UPDATE:
I realized I was sending in a JSON string and not necesarrily a JSON object...
so I changed the datatype to jsonstring from json...
still doesn't work.
Here is what returns my JSON data. UPDATED TO WHAT I AM NOW TRYING: I wanted to try putting the column names in the data... For some reason I thought that might help
public static object JsonHelper(TemplateModel model){
var values = model.Template;
var JsonDataList = new {
total = 1,
page = 1,
records = model.Template.Count,
rows = (from val in values
select new {
cell = //new string(
"[\"id\" :\"" + val.EncounterId +",\""+
//"\"MRN\" :" +
"\"MRN\" :\"" + val.MRN + ",\"" +
//"\"Hospital_Fin\" :" +
"\"Hospital_Fin\" :\"" + val.HostpitalFinNumber + ",\"" +
//"\"First_Name\" :"+
"\"First_Name\" :\"" + val.FirstName + ",\"" +
//"\"Last_Name\" :" +
"\"Last_Name\" :\"" + val.LastName + ",\"" +
//"\"Date_of_birth\" :" +
"\"Date_of_birth\" :\"" + val.DateOfBirth.ToString() + ",\"" +
//"\"Completed_Pathway\" :" +
"\"Completed_Pathway\" :\"" + val.CompletedPathway + ",\"" +
//"\"Completed_Pathway_Reason\" :" +
"\"Completed_Pathway_Reason\" :\"" + val.CompletedPathwayReason + ",\"" +
//"\"PCP_Appointment\" :" +
"\"PCP_Appointment\" :\"" + val.PCPAppointmentDateTime.ToString() + ",\"" +
//"\"Specialist_Appointment\" :" +
"\"Specialist_Appointment\" :\"" + val.SpecialistAppointmentDateTime.ToString() + ",\"" +
//"\"Admit_Date\" :" +
"\"Admit_Date\" :\"" + val.AdminDate.ToString() + "\"]"
})//.ToArray()
};
return JsonDataList;
}
plus...
return Json(DataRepository.JsonHelper(model.FirstOrDefault()), JsonRequestBehavior.AllowGet);
This is how I set up my jqGrid...
$(document).ready(function () {
$("#list").jqGrid({
shrinkToFit: false,
autowidth: true,
datatype: 'local',
mtype: 'POST',
colNames: ['Edit',
'MRN',
'Hospital Fin',
'First Name',
'Last Name',
'Date of birth',
'Completed Pathway',
'Completed Pathway Reason',
'PCP Appointment',
'Specialist Appointment',
'Admit Date'
],
colModel: [
{ name: 'Edit', width: 95, align: 'left' },
{ name: 'MRN', width: 125, align: 'left' },
{ name: 'Hospital_Fin', width: 145, align: 'left' },
{ name: 'First_Name', width: 115, align: 'left' },
{ name: 'Last_Name', width: 115, align: 'left' },
{ name: 'Date_of_birth', width: 145, align: 'left' },
{ name: 'Completed_Pathway', width: 125, align: 'left' },
{ name: 'Completed_Pathway_Reason', width: 165, align: 'left' },
{ name: 'PCP_Appointment', width: 115, align: 'left' },
{ name: 'Specialist_Appointment', width: 125, align: 'left' },
{ name: 'Admit_Date', width: 185, align: 'left' }],
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/Content/themes/UPMC-theme/images',
caption: 'My first grid'
}); })
I read somewhere online that setting the datatype to 'local' and then doing the setGridParam and trigger('reload') will help somehow or the other. Seems logical. But I am still a little unsure of how that would work... Still not working yet, but I am giving it the old college try...
UDPATE: Further explanation
My JsonHelper just tries to write out a valid JsonString... Does anybody have an example of how they do this regularly? Whenever I just use the standard Json ActionHelper thing... I guess I could make a different object return value, but that means I will have to mess around with more linq... And that is an adventure for another day.
**UPDATE2: Months have goneby"
Hello there. I have been distracted by another project for about a month. Now that it is starting to wind down, This code is starting to vex me once again. I feel like I am so close, but yet so far...
Anyway, Here is an example of the empty jqGrid that I was talking about...
As you can see, I have two rows of data, but neither one of them, has any of the data that they normally should...
Here is what the data looks like in debug mode...
["id" :"2005,""MRN" :"840108105,""Hospital_Fin" :"999999999999985,""First_Name" :"BETTY,""Last_Name" :"WHITE,""Date_of_birth" :"1/18/1951 12:00:00 AM,""Completed_Pathway" :",""Completed_Pathway_Reason" :",""PCP_Appointment" :"6/12/2012 12:00:00 AM,""Specialist_Appointment" :"6/12/2012 12:00:00 AM,""Admit_Date" :"7/5/2012 12:00:00 AM"]
["id" :"2025,""MRN" :"840108105,""Hospital_Fin" :"789654123000123,""First_Name" :"BETTY,""Last_Name" :"WHITE,""Date_of_birth" :"1/18/1951 12:00:00 AM,""Completed_Pathway" :",""Completed_Pathway_Reason" :",""PCP_Appointment" :"1/1/0001 12:00:00 AM,""Specialist_Appointment" :"1/1/0001 12:00:00 AM,""Admit_Date" :"7/6/2012 12:00:00 AM"]
That comes right out of my JSON helper... Which basically creates two string objects out of the Models that I get back...
This is what the JSON Data looks like on the client side right during the bind...
{"total":1,"page":1,"records":2,"rows":[{"cell":"[\"id\" :\"2005,\"\"MRN\" :\"840108105,\"\"Hospital_Fin\" :\"999999999999985,\"\"First_Name\" :\"BETTY,\"\"Last_Name\" :\"WHITE,\"\"Date_of_birth\" :\"1/18/1951 12:00:00 AM,\"\"Completed_Pathway\" :\",\"\"Completed_Pathway_Reason\" :\",\"\"PCP_Appointment\" :\"6/12/2012 12:00:00 AM,\"\"Specialist_Appointment\" :\"6/12/2012 12:00:00 AM,\"\"Admit_Date\" :\"7/5/2012 12:00:00 AM\"]"},{"cell":"[\"id\" :\"2025,\"\"MRN\" :\"840108105,\"\"Hospital_Fin\" :\"789654123000123,\"\"First_Name\" :\"BETTY,\"\"Last_Name\" :\"WHITE,\"\"Date_of_birth\" :\"1/18/1951 12:00:00 AM,\"\"Completed_Pathway\" :\",\"\"Completed_Pathway_Reason\" :\",\"\"PCP_Appointment\" :\"1/1/0001 12:00:00 AM,\"\"Specialist_Appointment\" :\"1/1/0001 12:00:00 AM,\"\"Admit_Date\" :\"7/6/2012 12:00:00 AM\"]"}]}
Just looking at my data, it seems kind of messed up. I am going to try and see if fixing it will make it look better. But if you have any other advice, I would definitely appreciate it.
I suppose that you have serious problems in the server code which you use. If you make $.ajax request with parameter dataType: "json" then $.ajax convert the data to the object. The response from the server seems as though you convert the returned object to JSON twice.
I suppose that you converted the object with total, page, records and rows properties first manually to JSON using JavaScriptSerializer or DataContractJsonSerializer and then returned the results string with return Json(myJsonString);. As the result the JSON string will be additionally encoded.
Moreover if you want use the data as datastr: result you have to use datatype: 'jsonstring' instead of datatype: 'json' which requires url parameter.
To tell the trust your code have other problems. $("#list").jqGrid({...}); create the grid from <table id="list"></table> element and the code can be executed only once. You current code is written so that the function bindData can be called multiple times on every form submit.
Additionally you use gridview: false which reduce the performance (you should always use gridview: true). The option imgpath not exist in jGrid since years. I suppose that you get some very very old example of jqGrid usage and tried to modify it to your purpose.
I would recommend you to get some more recent example, like from the answer or this one as the starting point. You should better use datatype: 'json' directly and send additional parameters to the server for example like it's described here or use $.serializeArray for example (see here).
UPDATED: There are NO JSON object. Either you have just an Object or you have a string which could represent an Object encoded corresponds to JSON standard.
You don't need to use any JsonHelper. The MVC action should just return Json(theObject) like
return new {
total = 1,
page = 1,
records = model.Template.Count,
rows = ...
};
Moreover the default format of JSON data for jqGrid described here. The code which you posted in JsonHelper contains
rows = (from val in values
select new {
invdata = new string[]{ ...}
}).ToArray()
and generate rows as array of objects without id property and with invdata property instead of cell. To read the data you need at least include jsonReader: {cell: "invdata"}. The better would be to return correct data having id. If some from the column tables could be interpreted as unique id of the row you can include key: true in the corresponding column, use jsonReader: {cell: ""} and fill rows as List<List<string>> or as array which elements as array or strings.
I think you are missing eval.
success: function (result) {
debugger;
var data = eval("(" + result.d + ")");
bindData(data);
}