Querying Child table with join from Parent returns duplicate records with JpaSpecificationExecutor - spring-data-jpa

looking for some help designing a solution for Search functionality using org.springframework.data.jpa.repository.JpaSpecificationExecutor interface.
Consider a Parent table(P) having columns ID, Name, UUID and some other columns specific to my application.
Now this Parent table has multiple child tables having one-to-many relation, linked via ID column of Parent table, say Child table 1 (C1) and so on.
My sample api request body:
{
"searchText": "",
"column1": ""
}
My requirement today is that the application should be able to perform an OR search between P.ID, P.Name, P.UUID and C1.column2 as part of "searchText" from above payload and then I also should be able to perform AND operation for every field provided in the payload.
Note that the fields in payload and the columns to which it belongs is fixed and cannot be given on runtime and search on fields other than searchText is working fine.
It was working fine till the application was supporting only P.ID, P.Name and P.UUID for searchText, but when I added C1.column2 in query using joins, it started returning duplicate entries as many number of times as the records present in C1 table for P.ID.
Looking for some suggestions for the implementation. Please let me know if my question is not clear or more information is required.

Related

Nest TypeORM Postgres update user's column('number of posts') based on the userId in the Posts Table

I'm wondering if it's possible to auto update the User's column('number of posts') if the Posts table updates. The Post entity has a ManyToOne relation with User('userId'). Is there a way to make the User Table "listen" to the Post Table and automatically updates the number of post column, or i need to write it in the post service create function to do so. I'm new to sql so i'm just trying new stuff. I'm using NestJS,typeORM, Postgres and Graphql
#Kendle's answer does work and has the advantage of pushing the computation and complexity down onto your DB server. Alternatively, you can keep that logic in the application by leveraging TypeORM's Subscribers functionality. Documentation can be found here.
In your specific use case, you could register a subscriber for your Post entity implementing afterInsert and afterRemove (or afterSoftRemove if you soft delete posts) to increment and the decrement the counter respectively.
You don't want to duplicate that data. That's the whole idea of a relational database that different data is kept in different tables.
You can create a view if you want to avoid typing a query with a JOIN each time.
For example you might create the view below:
CREATE VIEW userPosts AS
SELECT
user.id,
user.name,
COUNT(posts.id)
FROM users
LEFT JOIN posts ON user.id = posts.user_id
ORDER BY user.id;
Once you have created the view your can query it as if it were a table.
SELECT * FROM userDate WHERE id = '0001';
Of course I don't have your table definitions and data so you will need to adapt this code to your tables.

MS Access Filter Child Table by Record Chose on Form

I'm trying to create a simple 2 table database - table 1 holds ClientInfo and table 2 has ClientVisits - Relationship is on ClientInfo.ID->ClientVisits.ClientID. Then I have a form created thus for viewing the ClientInfo plus a child(sub?)table which SHOULD show all the records from ClientVisits where my Form ClientID = ClientVisits.ClientID.
Here is my form
Here is the child table with fields shown
Relationships
So I already have one record in ClientVisits for the currently chosen ClientID form record. But it doesn't show in my Table.ClientVisits. Other than the relationship I don't have any other link between the ClientID and the ClientVisits.ClientID field.
If I need to post further info please let me know, trying to describe this as well as I can - sorry if it's not making sense. Thanks.
You have to link both tables in your form.
In my example, main data of my form is a table called CLIENTES, where it shows all the information about a cliente. It would be exactly the same as your table ClientDetails. In this table, primary key is a field called DNI (it would be the equivalent of your ID field)
I got a second table called CONSULTAS MÉDICAS. This table is just a list of how many times this client comes to see us. It would be the same as your secondary table CLIENT VISITS. In this table, I got a field called PACIENTE, linked to my table CLIENTES. Let me show you.
Ok, now my form is done based on the data of my table CLIENTES, but I got a subform control, where I have linked the table CONSULTAS MÉDICAS
To make this work is pretty easy. Not filters or queries. Just linked child and master fields. To do this, you have to select properties of your subform control, and then go to DATA TAB
Just choose as main field your ID field from table CLIENT DETAILS and link it to child field CLIENT ID from table CLIENT VISITS
That should work for you.

Selecting columns from different entities

I don't know whether I should be drawing parallels, but unfortunately, that's the only way I can express my issue.
In SQL, suppose we have two tables:
Employee with columns Employee ID, Employee Name, Dept. ID
Deptartment with columns Dept. ID, Dept Name
The Dept ID. in the Employee table is a foreign key with that in the Department table.
Now suppose I want to fetch the following columns:
Employee ID, Employee Name, Department Name
using a SQL such as:
SELECT A.EMPLOYEE_ID, A.EMPLOYEE_NAME, B.DEPT_NAME
FROM EMPLOYEE A, DEPARTMENT B
WHERE A.DEPT_ID = B.DEPT_ID
How would one do this using Core Data in Swift? I guess I'm getting confused by only seeing references to
NSFetchRequest(entityName: entityName)
where the entityName refers to a single entity (table in relational DB lingo)
I'd really appreciate any pointers or examples that can help me clear my doubts.
Thanks
It is certainly possible to create a fetch request that is equivalent to your SQL query. More complex queries can be difficult if not impossible to achieve with a single fetch request. But I recommend trying NOT to draw parallels between CoreData and SQL, at least until you have got to grips with how it works.
To take your example, in the CoreData view of the world, Employee would be an entity with a relationship to another entity, Department. A fetch request based on the Employee entity will return an array of Employee objects, and (assuming you create subclasses of NSManagedObject for each entity) you can access the attributes with simple dot notation:
let employeeName = myEmployeeObject.employeeName
But you can use the same notation to traverse relationships equally easily:
let departmentName = myEmployeeObject.department.departmentName
You don't need to worry about joins, etc; CoreData handles that for you.
Now, suppose you try to do it "the SQL way". You can construct a fetch request based on the Employee entity, but specify "properties to fetch" which likewise traverse the relationship:
let fetch = NSFetchRequest(entity:"Employee")
fetch.propertiesToFetch = ["employeeID", "employeeName", "department.departmentName"]
For this to work, you would need to specify the "resultType" for the fetch request to be DictionaryResultType:
fetch.resultType = .DictionaryResultType
The results from this query would be an array of dictionaries containing the relevant keys and values. But the link with the underlying objects is lost. If you subsequently want to access any details from the relevant Department (or even the Employee), you would have to run a new fetch to get the object itself.

Entity Framework - best practice to get count

I have a Customer table and another Orders table. Each Customer can have many orders (One to many relationship).
I want to get a Customer object and from it get how many orders he has (the actual order data is not relevant at this point). So as I see it I have 2 options:
create a view with another OrdersCount field - and that will be another object in my system.
in my app, when I need the count get the Customer.Orders.Count - but for my understanding that will cause an extra query to run and pull all the orders from the database to that collection.
Is there a correct way to do such thing?
Thanks
You do need a new type, but you don't need to recreate all relevant properties.
from c in context.Customers
// where ...
select new {
Customer = c,
OrderCount = c.Orders.Count()
}
Update code that looks for e.g. the Name property of an item in the result, to look for Customer.Name.

Tough Sql Query problem involving family relationsships

i have a many to many table relationship that involves 2 logical tables.
Record table that joins to a relation table on primaryID
Second instance of record table that joins to the relation table on ReciprocalID
The purpose of this is to show family relations within the database. Each primary Record table has one or more rows in the relationtable that shows everyother family relationship this person has in the database.
I have been tasked with trying to make a contact list that involves displaying the names of each of the children that attend this school along with their parents and contact information.
I have gotten to a point where I am able to show the children under each parent, but now I have to find a way to merge these together.
Since I have no control over the design of this database(its Education Edge 7) I have made a separate database that holds my queries and views for my reports. The school I am doing this work for only has access to CR 8.5.
Right now I have my top group in CR as the lastname of the recordstable, my second group is on the fullname of the recordstable. I have a subreport that pulls in all the child records.
I have used a case when statement in my primary view(the one described above) to convert 'daughter' and 'son' to child and 'mother' or 'father' to parent.
hopefully this hasnt rambled too much. If you need anymore information just ask.
SELECT dbo.vwEA7RelationshipsTableView.PRIMARYID,
dbo.vwEA7RecordsTableView.LASTNAME AS PRIMARYLASTNAME,
dbo.vwEA7RecordsTableView.FIRSTNAME AS PRIMARYFIRSTNAME,
dbo.vwEA7RecordsTableView.NAMEFORDISPLAY AS PRIMARYNAME,
CASE dbo.vwEA7RelationshipsTableView.PRIMARYDESC
WHEN 'Father' THEN 'Parent'
WHEN 'Mother' THEN 'Parent'
WHEN 'Son' THEN 'Child'
WHEN'Daughter' THEN 'Child'
ELSE dbo.vwEA7RelationshipsTableView.PRIMARYDESC
END AS PRIMARYDESC,
dbo.vwEA7RelationshipsTableView.RELATIONID,
vwEA7RecordsTableView_1.LASTNAME AS RELATIONLASTNAME,
vwEA7RecordsTableView_1.NAMEFORDISPLAY AS RELATIONNAME,
dbo.vwEA7RelationshipsTableView.RELATIONDESC
FROM dbo.vwEA7RelationshipsTableView INNER JOIN
dbo.vwEA7RecordsTableView ON
dbo.vwEA7RelationshipsTableView.PRIMARYID = dbo.vwEA7RecordsTableView.ID INNER JOIN
dbo.vwEA7RecordsTableView AS vwEA7RecordsTableView_1 ON
dbo.vwEA7RelationshipsTableView.RELATIONID = vwEA7RecordsTableView_1.ID
TableViews are really just recreation of the primary tables from the main database.
I have solved this issue. My sql code was good, it was a matter of formatting my internal paramaters for Crystal as well as some creative grouping.