Hibernate, dealing with Criteria and left outer join condition - java

I've an existing piece of code like follow:
Criteria crit = session.createCriteria(myClass);
crit.createAlias(TAB1, TAB1, JoinType.LEFT_OUTER_JOIN);
crit.createAlias(TAB1 + ".table2", TAB2, JoinType.LEFT_OUTER_JOIN);
crit.add(Restrictions.eq(TAB1 + ".deleted", Boolean.FALSE));
crit.add(Restrictions.eq(TAB2 + ".id", someId));
This "generates" a sql query like follow:
SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id
WHERE tab1_.deleted=0
AND tab2_.id = 1234
I need to put filters in the JOIN condition rather than in the WHERE clause.
To be clear, I need to have the following query:
SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id AND tab1_.deleted=0
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id AND AND tab2_.id = 1234
How can I do this?
Thanks

You are using:
crit.createAlias(${table}, ${alias}, ${joinType});
You should be able to use:
crit.createAlias(${table}, ${alias}, ${joinType}, ${Criterion});
Although I could not find an example in our codebase, I would expect this to work.

Here is a decent example right from Hibernates confluence page:
public class PersonDao extends HibernateDaoSupport {
public List<Person> findByName() {
Criteria criteria = getSession().createCriteria(Person.class, "p");
criteria.createCriteria("p.names", "names", JoinType.INNER_JOIN, Restrictions.eq("name", "John"));
return criteria.list();
}
}
Produces
select this_.id as y0_ from person this_
inner join debtor_info this_1_ on this_.id=this_1_.id
left outer join person_person_name personname3_ on this_.id=personname3_.person_id and ( name1_.name=? )
left outer join person_name name1_ on personname3_.person_name_id=name1_.id and ( name1_.name=? )
With that example I believe your code should look something like
Criteria crit = session.createCriteria(MyClass.class, "mine");
crit.createAlias("mine.names", "name", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("name", Boolean.FALSE));
crit.createAlias("q.id", "id", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("id", someId));

Related

Is JPQL not the way to go for projections?

Here's my Repository method that I'm trying to call.
#Query(value = "select ise from InquirySession ise " +
"inner join ise.inquiryRequest.inquiryRequestFacilities irf " +
"left outer join ise.inquiryResponses ire on ire.facilityId = ?2 " +
"left outer join ire.responseActions ira " +
"left outer join ire.acceptDates irad " +
"left outer join ire.responseReasons irr " +
"where ise.carePathItem.id = ?1 and irf.facilityId = ?2")
Set<InquirySession> getAllByCarePathItemIdAndProviderId(final Long carePathItemId, final Long providerId);
My thought process was that when this method is executed, ise.inquiryResponses would be joined to InquirySession using the additional 'on' clause defined in the JPQL. However, I think this JPQL only selects InquirySession and does separate calls to join all other entities (defined in InquirySession) as I see separate sql statements after this one joining each entity using the primary/foreign key relationship.
Here's how InquiryResponse looks inside InquirySession
#OneToMany(mappedBy = "inquirySessionId")
#OrderBy(value = "createDate")
private Set<InquiryResponse> inquiryResponses;
and vice versa,
#Column(name = "inquirySessionDatabaseKey")
private Long inquirySessionId;
Is it possible to join InquiryResponse with the additional on clause ire.facilityId = ?2 when hydrating InquirySession entity using JPQL?
Edit
JPQL equivalent SQL
select inquiryses0_.inquirySessionId as inquirySessionId1_36_, inquiryses0_.carepathitemid as CarePat12_36_, inquiryses0_.createDate as createDa2_36_, inquiryses0_.description as descript3_36_,
inquiryses0_.fileSize as fileSize4_36_, inquiryses0_.documentLink as inquiryS5_36_, inquiryses0_.numberOfPages as numberOf6_36_, inquiryses0_.patientId as patientId7_36_,
inquiryses0_.patientEncounterId as patientV8_36_, inquiryses0_.patientplannerid as patientplannerid13_36_, inquiryses0_.purgedOn as purgedOn9_36_, inquiryses0_.amazonbucketname as s10_36_,
inquiryses0_.type as type11_36_
from InquirySession inquiryses0_
inner join InquiryRequest inquiryreq1_ on inquiryses0_.inquirySessionId=inquiryreq1_.inquirySessionId
inner join InquiryRequest_Facility inquiryreq2_ on inquiryreq1_.inquiryrequestid=inquiryreq2_.inquiryrequestid
left outer join InquiryResponse inquiryres3_ on inquiryses0_.inquirySessionId=inquiryres3_.inquirySessionId and (inquiryres3_.providerId=?)
left outer join InquiryResponse_Action_Link inquiryres3_1_ on inquiryres3_.inquiryresponseid=inquiryres3_1_.inquiryresponseid
left outer join InquiryResponseActions inquiryres4_ on inquiryres3_1_.inquiryresponseactionid=inquiryres4_.inquiryresponseactionid
left outer join InquiryResponse_AcceptDate_Link acceptdate5_ on inquiryres3_.inquiryresponseid=acceptdate5_.inquiryresponseid
left outer join InquiryResponse_Reason_Link responsere6_ on inquiryres3_.inquiryresponseid=responsere6_.inquiryresponseid
left outer join InquiryResponseReasons inquiryres7_ on responsere6_.responsereasonid=inquiryres7_.responsereasonid
where inquiryses0_.carepathitemid=? and inquiryreq2_.providerId=?
SQL that does not honor the 'on' clause and joins just on InquirySession.inquirySessionId
select inquiryres0_.inquirySessionId as inquirySessionId5_30_0_, inquiryres0_.inquiryresponseid as inquiryresponseid1_30_0_, inquiryres0_.inquiryresponseid as inquiryresponseid1_30_1_, inquiryres0_.createDate as createDa2_30_1_,
inquiryres0_.providerId as providerId3_30_1_, inquiryres0_.alsoCallMe as alsoCall4_30_1_, inquiryres0_.inquirySessionId as inquirySessionId5_30_1_, inquiryres0_.phoneNumber as phoneNum6_30_1_,
inquiryres0_.respondedBy as responde7_30_1_, inquiryres0_.responseText as response8_30_1_, inquiryres0_.responseTypeID as response9_30_1_,
inquiryres0_1_.inquiryresponseactionid as RSPNS_AC1_32_1_, inquiryres1_.inquiryresponseactionid as RSPNS_AC1_34_2_, inquiryres1_.inquiryresponseactiondescription as RSPNS_AC2_34_2_
from InquiryResponse inquiryres0_
left outer join InquiryResponse_Action_Link inquiryres0_1_ on inquiryres0_.inquiryresponseid=inquiryres0_1_.inquiryresponseid
inner join InquiryResponseActions inquiryres1_ on inquiryres0_1_.inquiryresponseactionid=inquiryres1_.inquiryresponseactionid
where inquiryres0_.inquirySessionId=? order by inquiryres0_.createDate
Looking at the first SQL, it's quite evident that the JPQL does not really care about joining other entities in InquirySession as all of the select statements are for InquirySession table. It does a separate SELECT statement to join InquiryResponse and thus, no longer has the expected additional ON clause.

While running Hibernate Criteria, HQL query is not created in given order

While running Hibernate Criteria, HQL query is not created in given order
and shows Exception
ERROR SqlExceptionHelper:131 - Unknown column 'stsup4_.SUPPLIER_ID' in 'on clause'
The Generated HQL is not created in expected order.
When I run the same generated HQL in mysql with some changes, I get output.
Java Code is given Below
Session session = connector.getSession();
Criteria cr = session.createCriteria(ST_PRODUCTMASTER.class, "ST_PRODUCT");
cr.createCriteria("ST_PRODUCT.ST_PRODUCT_MANUFACTURER_PARENT", "STPRODMAN", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("PROD_MAN_STATUS", "ACTIVE"));
cr.createCriteria("STPRODMAN.ST_MANUFACTURER", "STMAN", JoinType.LEFT_OUTER_JOIN);
cr.createCriteria("ST_PRODUCT.ST_PRODUCT_SUPPLIER_PARENT", "STPRODSUP", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("PROD_SUPPLIER_STATUS", "ACTIVE"));
cr.createCriteria("STPRODSUP.ST_SUPPLIER", "STSUP", JoinType.LEFT_OUTER_JOIN);
cr.createCriteria("ST_PRODUCT.ST_PRODUCT_RATES", "ZSTPR", JoinType.LEFT_OUTER_JOIN, Restrictions.eqProperty("ST_SUPPLIER.SUPPLIER_ID", "STSUP.SUPPLIER_ID"));
cr.createCriteria("ST_PRODUCT.ST_MEDICINE_CATEGORY", "MEDI_CAT", JoinType.LEFT_OUTER_JOIN);
cr.createCriteria("ST_PRODUCT.ST_TAX_MASTER", "TAX", JoinType.INNER_JOIN);
cr.createCriteria("ST_PRODUCT.ST_UNIT", "UNIT", JoinType.INNER_JOIN);
cr.add(Restrictions.eq("ST_PRODUCT.PRODUCT_STATUS", "ACTIVE"));
ProjectionList p1 = Projections.projectionList();
p1.add(Projections.property("ST_PRODUCT.PRODUCT_ID"));
p1.add(Projections.property("ST_PRODUCT.PRODUCT_NAME"));
p1.add(Projections.property("UNIT.UNIT_DISPLAY_UNIT"));
p1.add(Projections.property("TAX.TAX_PURCHASE"));
p1.add(Projections.property("ST_PRODUCT.PRODUCT2_DISCOUNT"));
p1.add(Projections.property("ST_PRODUCT.PRODUCT2_DIS_AMOUNT"));
p1.add(Projections.property("ST_MEDICINE_CATEGORY.CAT_CATEGORY_ID"));
p1.add(Projections.property("MEDI_CAT.CAT_SHORT_NAME"));
p1.add(Projections.property("UNIT.UNIT_ID"));
p1.add(Projections.property("TAX.TAX_ID"));
//MANUFACTURER
p1.add(Projections.property("STMAN.MAN_ID"));
p1.add(Projections.property("STPRODMAN.BASE_LEVEL"));
p1.add(Projections.property("STPRODMAN.FREE_QTY"));
//SUPPLIER
p1.add(Projections.property("STSUP.SUPPLIER_ID"));
p1.add(Projections.property("STPRODSUP.BASE_LEVEL"));
p1.add(Projections.property("STPRODSUP.FREE_QTY"));
cr.setProjection(p1);
List l = cr.list();
System.out.println("Size items::" + l.size());
ERROR SqlExceptionHelper:131 - Unknown column 'stsup4_.SUPPLIER_ID' in 'on clause'
This it the SQL generated by Hibernate
select
this_.PRODUCT_ID as y0_,
this_.PRODUCT_NAME as y1_,
unit8_.UNIT_DISPLAY_UNIT as y2_,
tax7_.TAX_PURCHASE as y3_,
this_.PRODUCT2_DISCOUNT as y4_,
this_.PRODUCT2_DIS_AMOUNT as y5_,
this_.CAT_CATEGORY_ID as y6_,
medi_cat6_.CAT_SHORT_NAME as y7_,
unit8_.UNIT_ID as y8_,
tax7_.TAX_ID as y9_,
stman2_.MAN_ID as y10_,
stprodman1_.BASE_LEVEL as y11_,
stprodman1_.FREE_QTY as y12_,
stsup4_.SUPPLIER_ID as y13_,
stprodsup3_.BASE_LEVEL as y14_,
stprodsup3_.FREE_QTY as y15_
from
ST_PRODUCTMASTER this_
left outer join
ST_MEDICINE_CATEGORY medi_cat6_
on this_.CAT_CATEGORY_ID=medi_cat6_.CAT_CATEGORY_ID
left outer join
ST_PRODUCT_MANUFACTURER stprodman1_
on this_.PRODUCT_ID=stprodman1_.PRODUCT_ID
and (
stprodman1_.PROD_MAN_STATUS=?
)
left outer join
ST_MANUFACTURER stman2_
on stprodman1_.MAN_ID=stman2_.MAN_ID
left outer join
ST_PRODUCT_RATES zstpr5_
on this_.PRODUCT_ID=zstpr5_.PRODUCT_ID
and (
zstpr5_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
)
left outer join
ST_PRODUCT_SUPPLIER stprodsup3_
on this_.PRODUCT_ID=stprodsup3_.PRODUCT_ID
and (
stprodsup3_.PROD_SUPPLIER_STATUS=?
)
left outer join
ST_SUPPLIER stsup4_
on stprodsup3_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
inner join
ST_TAX_MASTER tax7_
on this_.TAX_ID=tax7_.TAX_ID
inner join
ST_UNIT unit8_
on this_.UNIT_ID=unit8_.UNIT_ID
where
(
this_.PRODUCT_DELETED <> 'DELETED'
)
and this_.PRODUCT_STATUS=?
zstpr5_ is generated before stsup4_
and thus zstpr5_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
is not accessible
left outer join
ST_PRODUCT_RATES zstpr5_
on this_.PRODUCT_ID=zstpr5_.PRODUCT_ID
and (
zstpr5_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
)
left outer join
ST_PRODUCT_SUPPLIER stprodsup3_
on this_.PRODUCT_ID=stprodsup3_.PRODUCT_ID
and (
stprodsup3_.PROD_SUPPLIER_STATUS=?
)
left outer join
ST_SUPPLIER stsup4_
on stprodsup3_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
ACTUAL EXPECTED ORDER IS
left outer join
ST_PRODUCT_SUPPLIER stprodsup3_
on this_.PRODUCT_ID=stprodsup3_.PRODUCT_ID
and (
stprodsup3_.PROD_SUPPLIER_STATUS=?
)
left outer join
ST_SUPPLIER stsup4_
on stprodsup3_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
left outer join
ST_PRODUCT_RATES zstpr5_
on this_.PRODUCT_ID=zstpr5_.PRODUCT_ID
and (
zstpr5_.SUPPLIER_ID=stsup4_.SUPPLIER_ID
)
Hibernate is generating a number with table name,
1_, 2_ , 3_
even though while creating SQL this order is not maintained,
it is not even created in the order we give.
Since you haven't posted your mapping file, I'll explain how Hibernate orders the joins.
Hibernate uses the mapping xml file to figure out the order of joins, so if you have a relation in it (one-to-many or any other tag) for that table, just move it above the other table's tag.
You can read more about it here.

How to implement following multiple inner join in hibernate?

I hava query:
Hibernate: select this_.pName as y0_, this_.kNum as y1_, count(*) as y2_ from ALL_CPView this_ inner join ALL_AMView aID1_ on this_.agentid=aID1_.AgentID
and criteria,
Criteria crit = statelessSession.createCriteria(APRecord.class, "apr")
.createAlias("manageID", "ID", Criteria.INNER_JOIN);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("PName"), "PName")
.add(Projections.groupProperty("kNum"), "kNum")
.add(Projections.rowCount() , "count"));
results = crit.setResultTransformer(Transformers.aliasToBean(APStat.class)).list();
How can I add another projection with distinct count for aID with the inner join?

Hibernate DetachedCriteria Query with and clause in subselect

How can I solve this query with Hibernate's detached criteria? The hardest part for me is to bring the and u1.abrechnungsDatum is null into the subselect.
I want a query like this:
select *
from
patient as p
where
p.krankenstand = ?
and
? < ( select count(*) from ueberweisung u1 where p.id = u1.patient_id
and u1.abrechnungsDatum is null)
I have tried it with this
DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient");
dc.add(Restrictions.eq("krankenstand", true));
DetachedCriteria nab = dc.createCriteria("ueberweisungs", "nab");
nab.add(Restrictions.isNull("nab.abrechnungsDatum"));
dc.add(Restrictions.sizeGt("ueberweisungs", 0));
which gives me the following SQL-Statement
select
*
from
patient this_
inner join
ueberweisung nab1_
on this_.id=nab1_.patient_id
where
this_.krankenstand=?
and nab1_.abrechnungsDatum is null
and ? < (
select
count(*)
from
ueberweisung
where
this_.id=patient_id
)
As you can see, the and-clause for the field abrechnungsDatum is not inside the subselect. How can I achieve to get this inside?
Try this instead:
DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient");
dc.add(Restrictions.eq("krankenstand", true));
DetachedCriteria subquery = DetachedCriteria.forClass(Ueberweisung.class);
subquery.add(Restrictions.isNull("abrechnungsDatum"));
dc.add(Subqueries.ltAll(0, subquery));

HQL to Criteria

I am trying to create a Criteria from HQL.
Simplified HQL:
SELECT
event.pkid,
add.name
FROM Event event
LEFT JOIN event.addresses adds
JOIN adds.address add
WHERE adds is null
or adds.addressType = 'EVENT'
And I use following Criteria to produce an equivalent query.
criteria.createAlias("addresses", "adds",
CriteriaSpecification.LEFT_JOIN)
.createAlias("adds.address", "add",
CriteriaSpecification.LEFT_JOIN)
.setProjection(
Projections
.projectionList()
.add(Projections.property("pkid"))
.add(Projections
.property("add.name")))
.add(Restrictions.or(Restrictions.isNull("addresses"),
Restrictions.eq(
"adds.addressType.addressType",
"EVENT")));
But it produces following query,
select
this_.pkid as y0_,
add2_.name as y1_
from event this_
left outer join event_address_map adds1_ on this_.pkid=adds1_.event_pkid
where (this_.pkid is null or adds1_.address_type=?)
Second join is not added. What am I doing wrong?
Thanks in advance.

Categories