I have two tables as below:
Student: oneID (primary key), col1, col2, col3, subId, col4
Subject: subID (primary key), col1, col2
Every student will have exactly one or none of the subjects assigned.
So in the case: one subject assigned: subId in Student will have some value which maps to subID in Subject table
and in the case: 0 subject assigned: subId in Student will be null.
With above scenario, I have a left join query as below:
select st.col1, st.col2, su.col1, su.col2 from Student st left join Subject su on st.subId = su.subId where st.oneId = 'abc'
How to write the same exact query in Hibernate ?
select st.col1, st.col2, su.col1, su.col2 from Student st left join st.sub as su where st.oneId = 'abc'
Above query does not work and gives the below error:
"org.hibernate.hql.ast.QuerySyntaxException: Path expected for join!"
What am I missing ?
In my java code I have kept both the tables independent. That is there is no relationship between the tables defined.
Persistence.xml is as below:
<persistence-unit name="myEntityManager" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.myPackage.Student</class>
<class>com.myPackage.Subject</class>
</persistence-unit>
POJOs are as below:
Student
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {
@Id
@Column(name = "ONEID")
private String oneId;
private Subject sub;
//other columns here
public void setSub(final Subject sub) {
this.sub = sub;
}
@OneToOne(cascade = CascadeType.ALL)
public Subject getSub() {
return this.sub;
}
}
Subject
@Entity
@Table(name = "SUBJECT")
public class Subject implements Serializable {
@Id
@Column(name = "SUBID")
private String subId;
//other columns here
}
As mentioned in this hibernate forum thread, it’s currently not possible in Hibernate to invoke left join on disassociated entities. There’s also an opened Hibernate issue for it.
What you should do instead, is define a
one-to-oneorone-to-manyrelationship betweenStudentandSubject(one-to-one example, many-to-one example).Then, try this HQL, assuming the reference in
Studentto its subjects is namedsubjects:select st.col1, st.col2, su.col1, su.col2 from Student st left join st.subjects su where st.oneId = 'abc'