How to map jooq result to their respective entities - mysql

I have this SQL query:
select question.*,
question_option.id
from question
left join question_option on question_option.question_id = question.id;
How do I map the result obtained to the entity. so that the expected result should be like
Can anyone give the sample code for getting the result as above
{
"id": 2655,
"type": "MCQSingleCorrect",
"difficultyLevel": "Advanced",
"question": "Which country are you from?",
"answer": null,
"marks": 1.5,
"negativeMarks": 0.5,
"hint": null,
"explanation": null,
"booleanAnswer": null,
"passage": null,
"isPassageQuestion": null,
"audioFile": null,
"videoFile": null,
"questionFiles": [],
"tags": [],
"updatedAt": "2021-12-21T11:57:03.229136Z",
"createdAt": "2021-12-21T11:57:03.229098Z",
"questionOptions": [
{
"id": 2719,
"option": "India",
"index": 1,
"correct": false,
"blank": null
},
{
"id": 2720,
"option": "Newzealand",
"index": 1,
"correct": false,
"blank": null
},
{
"id": 2721,
"option": "England",
"index": 1,
"correct": true,
"blank": null
},
{
"id": 2722,
"option": "Australia",
"index": 1,
"correct": false,
"blank": null
}
]}

I'm answering from the perspective of our comments discussion, where I suggested you don't need JPA in the middle, because you can do every mapping / projection with jOOQ directly. In this case, if you're targeting a JSON client, why not just use SQL/JSON, for example? Rather than joining, you nest your collection like this:
ctx.select(jsonObject(
key("id", QUESTION.ID),
key("type", QUESTION.TYPE),
..
key("questionOptions", jsonArrayAgg(jsonObject(
key("id", QUESTION_OPTION.ID),
key("option", QUESTION_OPTION.OPTION),
..
)))
))
.from(QUESTION)
.leftJoin(QUESTION_OPTION)
.on(QUESTION_OPTION.QUESTION_ID.eq(QUESTION.ID))
// Assuming you have a primary key here.
// Otherwise, add also the other QUESTION columns to the GROUP BY clause
.groupBy(QUESTION.ID)
.fetch();
This will produce a NULL JSON array if a question doesn't have any options. You can coalesce() it to an empty array, if needed. There are other ways to achieve the same thing, you could also use MULTISET if you don't actually need JSON, but just some hierarchy of Java objects.
As a rule of thumb, you hardly ever need JPA in your code when you're using jOOQ, except if you really rely on JPA's object graph persistence features.

You can write the query with jOOQ and the do this:
Query result = em.createNativeQuery(query.getSQL());
query.getResultList() // or query.getSingleResult() depending what you need.
Read more here:
https://www.jooq.org/doc/3.15/manual/sql-execution/alternative-execution-models/using-jooq-with-jpa/using-jooq-with-jpa-native/
JSON can be fetched directly using SQL (and also jOOQ). Here are some examples:
https://72.services/use-the-power-of-your-database-xml-and-json/

Related

JSONata Filter Array by starts-with criteria

I'm pretty new to JSONata, and I need to write a query that will search/filter an array and return only the values that meet the criteria.
Specifically:
{
"data": [
{
"externalIds": [
"005262615581",
"1395464646",
"566955222",
"6696630050055999",
"99506533221233"
],
"firstName": "Brian",
"id": "a91f91af91af91a9f11fakeid",
"lastName": "lastName",
"office": null,
"phone": null,
"role": "Admin",
}
]
}
I've tried $Contains, and $Filter, but I honestly don't know the syntax to accomplish the "starts-with" concept.
I need to filter the "externalIds" array and only return the IDs that begin with 005, NOT contain 005.
So in this body I need it to return "005262615581".
You can use regular expressions and the $match function:
data.externalIds[$match($, /^005/)]
See it live on the playground: https://stedi.link/fa5C2GZ

convert null values corresponding to an Array to empty array in nifi jolt

I want to achieve following JSON transformation using Jolt processor in NIFI
By focusing on values field, in the first input in json (id 900551), values are populated as the following
input JSON
{
"id": 900551,
"internal_name": [],
"values": [
{
"id": 1430156,
"form_field_id": 900551,
"pos": 0,
"weight": null,
"category": null,
"created_at": "2020-10-15 12:55:02",
"updated_at": "2020-11-27 10:45:09",
"deleted_at": null,
"settings": {
"image": "myimage.png"
"fix": false,
"bold": false,
"exclusive": false
},
"internal_value": "494699DV7271000,6343060SX0W1000,619740BWR0W1000",
"css_class": null,
"value": "DIFFERENCE",
"settings_lang": {},
"value_html": ""
}
]
}
On the second input Json file to parse, values is null.
{
"id": 900552,
"internal_name": [],
"values": []
}
I would like to convert null values to an empty array in my conversion
Is there a way to do this using existing Jolt operations ?
Thanks.
The default operation is what you are looking for:
Defaultr walks the spec and asks "Does this exist in the data? If not, add it."
In our case:
if the value for "values" key is null, put the empty array instead
Here is the spec:
[
{
"operation": "default",
"spec": {
"values": []
}
}
]
tested with https://jolt-demo.appspot.com/
edit: answering the question from the comment:
Maybe this workaround will work for you

Is there a way to UPDATE values based on WHERE conditions between two JSON files

Say I have two versions of the same JSON data. Each object has a unique ID key/pair. Say in one version a certain key has null as its value while the other version has the appropriate values for that key.
Can we match the objects between the two JSON files based on their unique ID value and copy over a certain key's values? I don't want to mess around with the rest of the fields in the JSON object.
Sample:
version 1:
[
{
"contentId": "ID-02",
"title": "Attendance",
"desp": "Daily Attendance",
"contentType": "service",
"url": "ATTENDANCE",
"contentCategory": "Essentials",
"employeeId": null,
"imageUrl": null,
"publishedCourseFlag": "true"
},
{
"contentId": "ID-04",
"title": "Regularise History",
"desp": "Regularise History",
"contentType": "service",
"url": "REGULARISE_HISTORY",
"contentCategory": "Non-Essentials",
"employeeId": null,
"imageUrl": null,
"publishedCourseFlag": "false"
}
]
version 2:
[
{
"contentId": "ID-02",
"title": "Attendance",
"desp": "Daily Attendance",
"contentType": "service",
"url": "ATTENDANCE",
"contentCategory": null,
"employeeId": null,
"imageUrl": null
},
{
"contentId": "ID-04",
"title": "Regularise History",
"desp": "Regularise History",
"contentType": "service",
"url": "REGULARISE_HISTORY",
"contentCategory": null,
"employeeId": null,
"imageUrl": null,
"publishedCourseFlag": "false"
}
]
Here v1 has the contentCategory set while v2 has null. I want to copy the appropriate values from v1 to v2 based on their contentId values. Is there a simple way to do this other than manually copy/paste? I'd like a scripting solution that I can modify to my needs for situations like this. Or a simple query like solution would be even better.
Additionally is it possible to add a certain missing key/value from version 1 to version 2 ? Like Update if present else Insert ? I am hoping for a lot I guess. Completely new to JSON.

Work around for sequelize boolean value from mysql database

I am getting data from mysql database to express rest api app. Using sequelize as a ORM.
When it is comes to a BIT(1) value from mysql, sequelize returns a instance of buffer object.
{
"id": 4,
"ProductPrice": 12.25,
"ProductQuantityOnHand": 0,
"ProductCode": "P486",
"ProductName": "FirstProduct",
"ProductDescription": null,
"ProductActive": {
"type": "Buffer",
"data": [
1
]
},
"createdAt": "2019-02-02T11:27:00.000Z",
"updatedAt": "2019-02-02T11:27:00.000Z"
}
Like here product active a BIT(1) and sequelize returning a object.
How can I get boolean value instead of an object?
Like this.
{
"id": 4,
"ProductPrice": 12.25,
"ProductQuantityOnHand": 0,
"ProductCode": "P486",
"ProductName": "FirstProduct",
"ProductDescription": null,
"ProductActive": true,
"createdAt": "2019-02-02T11:27:00.000Z",
"updatedAt": "2019-02-02T11:27:00.000Z"
}
I might suggest that you just use an INT column in your MySQL table. Assuming you only store values 0 and 1, these same values should show up in your ORM/application layer.
As the value 0 is "falsy" in JavaScipt, it would logically behave the same way as false, and vice-versa for 1, which is "truthy."

Access deeper elements of a JSON using postgresql 9.4

I want to be able to access deeper elements stored in a json in the field json, stored in a postgresql database. For example, I would like to be able to access the elements that traverse the path states->events->time from the json provided below. Here is the postgreSQL query I'm using:
SELECT
data#>> '{userId}' as user,
data#>> '{region}' as region,
data#>>'{priorTimeSpentInApp}' as priotTimeSpentInApp,
data#>>'{userAttributes, "Total Friends"}' as totalFriends
from game_json
WHERE game_name LIKE 'myNewGame'
LIMIT 1000
and here is an example record from the json field
{
"region": "oh",
"deviceModel": "inHouseDevice",
"states": [
{
"events": [
{
"time": 1430247045.176,
"name": "Session Start",
"value": 0,
"parameters": {
"Balance": "40"
},
"info": ""
},
{
"time": 1430247293.501,
"name": "Mission1",
"value": 1,
"parameters": {
"Result": "Win ",
"Replay": "no",
"Attempt Number": "1"
},
"info": ""
}
]
}
],
"priorTimeSpentInApp": 28989.41467999999,
"country": "CA",
"city": "vancouver",
"isDeveloper": true,
"time": 1430247044.414,
"duration": 411.53,
"timezone": "America/Cleveland",
"priorSessions": 47,
"experiments": [],
"systemVersion": "3.8.1",
"appVersion": "14312",
"userId": "ef617d7ad4c6982e2cb7f6902801eb8a",
"isSession": true,
"firstRun": 1429572011.15,
"priorEvents": 69,
"userAttributes": {
"Total Friends": "0",
"Device Type": "Tablet",
"Social Connection": "None",
"Item Slots Owned": "12",
"Total Levels Played": "0",
"Retention Cohort": "Day 0",
"Player Progression": "0",
"Characters Owned": "1"
},
"deviceId": "ef617d7ad4c6982e2cb7f6902801eb8a"
}
That SQL query works, except that it doesn't give me any return values for totalFriends (e.g. data#>>'{userAttributes, "Total Friends"}' as totalFriends). I assume that part of the problem is that events falls within a square bracket (I don't know what that indicates in the json format) as opposed to a curly brace, but I'm also unable to extract values from the userAttributes key.
I would appreciate it if anyone could help me.
I'm sorry if this question has been asked elsewhere. I'm so new to postgresql and even json that I'm having trouble coming up with the proper terminology to find the answers to this (and related) questions.
You should definitely familiarize yourself with the basics of json
and json functions and operators in Postgres.
In the second source pay attention to the operators -> and ->>.
General rule: use -> to get a json object, ->> to get a json value as text.
Using these operators you can rewrite your query in the way which returns correct value of 'Total Friends':
select
data->>'userId' as user,
data->>'region' as region,
data->>'priorTimeSpentInApp' as priotTimeSpentInApp,
data->'userAttributes'->>'Total Friends' as totalFriends
from game_json
where game_name like 'myNewGame';
Json objects in square brackets are elements of a json array.
Json arrays may have many elements.
The elements are accessed by an index.
Json arrays are indexed from 0 (the first element of an array has an index 0).
Example:
select
data->'states'->0->'events'->1->>'name'
from game_json
where game_name like 'myNewGame';
-- returns "Mission1"
select
data->'states'->0->'events'->1->>'name'
from game_json
where game_name like 'myNewGame';
This did help me