Hibernate Criteria: Left Outer Join with restrictions on both tables

醉酒当歌 提交于 2019-12-12 07:26:24

问题


I am doing a LEFT OUTER JOIN, but I am only able to apply Restrictions on the first table. Is there a way ti apply on the second table as well?

Here is my code:

Criteria criteria = this.crudService
        .initializeCriteria(Applicant.class).setFetchMode("products",
              FetchMode.JOIN);.

This works (applicant has an applicantName property):

criteria.add(Restrictions.eq("applicantName", "Markos")

Neither of these works (product has a productName property)

criteria.add(Restrictions.eq("productName", "product1")

criteria.add(Restrictions.eq("products.productName", "product1") // products: the name of the property criteria.add(Restrictions.eq("Product.productName", "product1") // Product: the name of the DB table

And this is the exception I am receiving saying (if I understand correctly) that the productName property does not exist in Applicant:

EJB Exception: ; nested exception is: org.hibernate.QueryException: could not resolve property: products.inventedName of: org.myCompany.applicant.entity.Applicant; nested exception is: org.hibernate.QueryException: could not resolve property: products.inventedName of: org.myCompany.applicant.entity.Applicant

I tried to use an alias, but this generated an INNER JOIN, instead of the LEFT OUTER JOIN I want.

How can I apply restrictions on both tables?

UPDATE:

Issue is probably the same as this: https://forum.hibernate.org/viewtopic.php?p=2393694


回答1:


You can specify left outer join in the createalias...

.CreateAlias("products", "p", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.Add(Restrictions.Eq("p.inventedName", inventedName));

Be aware that you are doing a left outer join with a restriction on that column...essentially making it an inner join. If you also want applicants without products then you'll have to check for null product too.




回答2:


Update:

.CreateAlias("products", "p", JoinType.LEFT_OUTER_JOIN)
.Add(Restrictions.Eq("p.inventedName", inventedName));



回答3:


I solved this my problem creating a new criteria and I could use LEFT_OUTER_JOIN in both cases.



来源:https://stackoverflow.com/questions/2208201/hibernate-criteria-left-outer-join-with-restrictions-on-both-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!