I have a table which can referance on itself.
organisation(id,child_from_Org, ...)
Hibernate Mapping
@Entity
@Table(name = "organisation")
public class Organisation implements java.io.Serializable {
private Integer id;
private Organisation organisation;
private ...
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "child_from_Org")
public Organisation getOrganisation() {
return this.organisation;
}
public void setOrganisation(Organisation organisation) {
this.organisation = organisation;
}
...
}
If i execute aa hibernate query like "from Organisation", then i'll get all organisations.
from Organisation o where o.id = 1
Then i get the organisation with id 1
from Organisation o where o.id = 1 or o.organisation.id = 1
Returns organisation with id 1 and all child organisations
from Organisation o where o.id = 1 or o.organisation.id = 1 or o.organisation.organisation.id = 1
Does not return the organisation with id 1!!!! Why? I tried all possible combinations with braclets (() or () or ()).
I looks like a wrong SQL is getting generated from hibernate:
select organisati0_.id as id470_,
organisati0_.child_from_Org as ist21_470_,70_,
,...
from
organisation organisati0_ cross
join
organisation organisati1_
where
organisati0_.child_from_Org=organisati1_.id
and (
organisati0_.id=1
or organisati0_.child_from_Org=1
or organisati1_.child_from_Org=1
)
How can i resolve that problem?
Because you have an implicit join from Organisation
to itself, and in hibernate implicit joins are inner joins:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins-forms
The implicit form does not use the join keyword. Instead, the associations are "dereferenced" using dot-notation. implicit joins can appear in any of the HQL clauses. implicit join result in inner joins in the resulting SQL statement.
Try explicit left joins, eg:
select o from Organisation as o left join o.organisation as parent left join parent.organisation as grandparent where o.id = 1 or parent.id = 1 or grandparent.id = 1
( NOTE: I've assumed organization.organisation is a parent relationship. If that's not the case you can(and should) replace the parent
and grandparent
aliases with something more appropriate)
EDITED TO ADD:
It seems what's happening is that the inner join is ruling out org with id of 1, probably because org with id of 1 has a null organisation
EDITED AGAIN TO ADD: Added select per comment below.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.