JPQL LEFT JOIN is not working - jpql

I want to get the list of all Branch even if they have no accounts with user role
Query query = em.createQuery("SELECT NEW com.package.BranchInstructors(b,a) FROM Branch b LEFT JOIN b.accounts a WHERE b.dFlg = 0 AND a.userRole = :role ORDER BY b.name ASC");
query.setParameter("role", "user");
return query.getResultList();
Unfortunately it's returning only Branches with user role, it's like doing INNER JOIN instead.
Any idea what's going on?

just add the a.userRole is null condition to your query to avoid filtering the null userRole that you got from the left join
SELECT NEW com.package.BranchInstructors(b,a)
FROM Branch b
LEFT JOIN b.accounts a
WHERE b.dFlg = 0
AND (a.userRole = :role OR a.userRole IS NULL)
ORDER BY b.name ASC"

The problem is in your WHERE vs LEFT JOIN clause.
If you use LEFT JOIN table Accounts and use this table in the WHERE with AND condition, it behaves like a JOIN.
So, you can use WITH in the LEFT JOIN:
Query query = em.createQuery("SELECT NEW com.package.BranchInstructors(b,a) FROM Branch b
LEFT JOIN b.accounts a WITH a.userRole = :role
WHERE b.dFlg = 0 ORDER BY b.name ASC");

Related

How to search with each starting letter of words in sequelize

I want to get search results if my string is "customer details" .I am able to do a search if I type cust will get desired output but if I search using data keyword. I am getting no results. How to achieve with sequelize?
What I have tried -
sequelize.where(sequelize.fn('LOWER', sequelize.col('name')), 'LIKE', queryObj.keyword.toLowerCase() + '\%')
Generated Query
SELECT "Campaign"."id" FROM "Campaigns" AS "Campaign" LEFT OUTER JOIN "EmailCampaigns" AS "EmailCampaigns" ON "Campaign"."id" = "EmailCampaigns"."campaignId" AND ("EmailCampaigns"."deletedAt" IS NULL)
LEFT OUTER JOIN "CampaignEmailTemplates" AS "CampaignEmailTemplate" ON "Campaign"."id" = "CampaignEmailTemplate"."campaignId"
AND ("CampaignEmailTemplate"."deletedAt" IS NULL)
LEFT OUTER JOIN "CampaignScheduleRequests" AS "CampaignScheduleRequest" ON "Campaign"."id" = "CampaignScheduleRequest"."campaignId"
AND ("CampaignScheduleRequest"."deletedAt" IS NULL)
LEFT OUTER JOIN "CampaignStats" AS "CampaignStat" ON "Campaign"."id" = "CampaignStat"."campaignId" AND ("CampaignStat"."deletedAt" IS NULL)
WHERE ("Campaign"."deletedAt" IS NULL AND ("Campaign"."accountId" = 403
AND LOWER("Campaign"."name") iLIKE 'cust%')) ORDER BY "Campaign"."updatedAt" DESC;
sequelize.where(sequelize.fn('LOWER', sequelize.col('name')), {[Op.like]: `%${queryObj.keyword.toLowerCase()}%`}),
I found the way can be achieved by
sequelize.where(sequelize.fn('LOWER', sequelize.col('name')), {[Op.iRegexp]: `\\y${queryObj.keyword.toLowerCase()}.*\\y`})

HYBRIS Flexible Query to get all the products from Order Model

My requirement is to get the list of customers who have ordered an old product.
Here for the old product, we are using an attribute "endproduct".
I am able to get all the customers who have placed orders. BUT I don't know how to create a query to get products from Order Model.
I have run this query :
SELECT distinct {c:uid},{aeo:product} from
{customer as c JOIN order as o on {c:pk}={o:user}JOIN AbstractOrder as ao on {o:pk}={ao:pk} JOIN AbstractOrderEntry as aeo on {ao:pk}={aeo:pk}}
Because AbstractOrderEntryModel has a product attribute.
Try like
SELECT
distinct {u:uid},{p:name}
FROM { Order AS o JOIN OrderEntry AS oe ON {o.pk} = {oe.order} JOIN Product AS p ON {p.pk} = {oe.product} and {p.endproduct} = '1' JOIN User AS u ON {o.user} = {u.pk}}
Change endproduct condition as per your requirement.
Try below query, it should give expected results.
select {c.uid},{p.code}
from {Customer as c}, {Order as o}, {Product as p}, {AbstractOrderEntry as ao}
where {o.user} = {c.pk} and {o.pk} = {ao.order} and {ao.product} = {p.pk}

Cosmos DB Left Join

All of the documentation for Cosmos DB and it looks like it only supports the JOINkeyword, which seems to be a sort of INNER JOIN.
I have the following query:
SELECT * FROM
(
SELECT
DISTINCT(c.id),
c.OtherCollection,
FROM c
JOIN s IN c.OtherCollection
)
AS c order by c.id
This works fine and returns the data of documents that have OtherCollection populated. But It obviously does not return any documents that do not have it populated.
The reason for the join is that sometimes I execute the following query (queries are built up from user input)
SELECT * FROM
(
SELECT
DISTINCT(c.id),
c.OtherCollection,
FROM c
JOIN s IN c.OtherCollection
WHERE s.PropertyName = 'SomeValue'
)
AS c order by c.id
The question is how can I have a sort of LEFT JOIN operator in this scenario?
CosmosDB JOIN operation is limited to the scope of a single document. What possible is you can join parent object with child objects under same document.
It is totally different from SQL Join query which supports across two/many tables.
You can simulate LEFT JOIN with the EXISTS sentence.
Eg:
SELECT VALUE c
FROM c
WHERE (
(c.OtherCollection = null) OR EXISTS (--Like a "Left Join"
SELECT null
FROM s IN c.OtherCollection
WHERE s.PropertyName = 'SomeValue'
)
)
--AND/OR Some other c Node conditions
order by c.id

Complex sql query and JPQL

How to change this complex sql statement into JPQL?
select a.name, a.surname, b.street, c.location, c.location_desc
from table1 join table2 on b.id = a.some_fk
left join table3 d on d.id = a.id
left join table4 c on c.some2_id = d.some2_fk where a.id = 400;
If this is possible to present in the JPQL form?
Impossible to give a definitive answer without knowing the entities and their mapping, but the query would look like this:
select a.name, a.surname, b.street, c.location, c.locationDesc
from Entity1 a
join a.entity2 b
left join a.entity3 d
left join d.entity4 c
where a.id = 400;
provided the necessary associations between entities are there.
JPQL is object oriented, it operates against JPA entity objects ,not database tables. Either you need to change the Question and add an UML diagramm or provide the Entity classes.

Converting a LEFT OUTER JOIN to Entity Framework

Here is a SQL Query I want to convert to EF4.3
command = database.GetSqlStringCommand(#"
select
H.AUTHENTICATION_ID,
USERNAME,
PERMISSIONS,
ORGANIZATION_IDENTIFIER,
O.ORGANIZATION_ID
from
AUTHENTICATION H
left join [AUTHORIZATION] T on H.AUTHENTICATION_ID=T.AUTHENTICATION_ID
join ORGANIZATION O on O.ORGANIZATION_ID = T.ORGANIZATION_ID
order by H.AUTHENTICATION_ID");
Here is the best LINQ I could come up with:
var query = from h in context.Authentications
join t in context.Authorizations on h.AuthenticationId equals t.Authentications.AuthenticationId
join o in context.Organizations on t.Organizations.OrganizationId equals o.OrganizationId
orderby
h.AuthenticationId
select new
{ AUTHENTICATION_ID = (Int16?)h.AuthenticationId,
h.Username,
t.Permissions,
o.OrganizationIdentifier,
OrganizationID = (Int16?)o.OrganizationId
};
I know i need to merge my first join (between Authorizations & Authentications) into, lets say x and apply DefaultIfEmpty but can't make out the syntax.
EDIT: Image for clarification:
Any help will be highly appreciated. Regards.
The basic syntax for a "left join" in Linq is like this:
from x in table1
join y in table2 on x.id equals y.id into jointable
from z in jointable.DefaultIfEmpty()
select new
{
x.Field1,
x.Field2,
x.Field3,
Field4 = z == null ? 0 : z.Field4
};
In your case, I'm a little confused because the entity relations you seem to be using in your Linq don't match the ones implied by your SQL; are the relationships here zero-or-one, zero-or-many, one-to-one, etc? Specifically, you're doing this:
from h in context.Authentications
join t in context.Authorizations on h.AuthenticationId equals t.Authentications.AuthenticationId
but your SQL implies that "Authentication" is the parent here with zero-or-more "Authorization" children, not the other way around, which would be more like:
from h in context.Authentications
from t in h.Authorizations.DefaultIfEmpty()
If you can give us a better idea of the data model and what data you expect to get out of it we can more easily explain how that query would look in Linq. Assuming that your relationships match what is implied by the SQL, you should be able to get what you want using the following Linq queries:
var query = from h in context.Authentications
from t in h.Authorizations.DefaultIfEmpty()
select new
{
h.AuthenticationId,
h.Username,
Permissions = t == null ? null : t.Permissions,
Organizations = t == null ? new EntitySet<Organization>() : t.Organizations
};
var query2 = from x in query
from o in x.organizations.DefaultIfEmpty()
select new
{
AUTHENTICATION_ID = (short?)x.AuthenticationId,
x.Username,
x.Permissions,
OrganizationIdentifier = o == null ? null : o.OrganizationIdentifier,
OrganizationID = o == null ? (short?)null : o.OrganizationID
};
Given the foreign keys that exist in the question diagram, how about something like this?
var query = from a in context.Authentications
select new
{
a.AuthenticationID,
a.Username,
a.Authorisations.Permissions ?? false,
a.Authorisations.Organisations.OrganisationIdentifier ?? 0
a.Authorisations.Organisations.OrganisationID ?? 0
};
I went ahead and moved the entire query to a Stored Procedure on the database. This solves the problem by avoiding LINQ and ObjectBuilder in the first place.

Resources