I am confused about how Criteria.setFetchMode() is supposed to be used.
I've setup two simple classes: A and B.
Class A contains an instance of Class B.
Each class has one other property and an ID.
A has a name (String).
B has a color (String).
My data looks like the following:
A:
id name b_id
1 foo <null>
2 bar 2
B:
id color
1 red
2 green
3 blue
I would like to fetch a list of "A" objects ordered by color.
My beans look like this:
public class A {
protected String id;
protected String name;
protected B b;
public A () {
// instantiate a new association entity if it is null
if (b == null) {
b = new B();
}
}
public A (
String pId, String pName, Long pBId) {
this.setId(pId);
this.setName(pName);
this.setBId(pBId);
}
public String getId() {
return this.id;
}
public void setId(String pId) {
this.id = pId;
}
public String getName() {
return this.name;
}
public void setName(String pName) {
this.name = pName;
}
public String getBId() {
if (b == null) {
return null;
}
return this.getB().getId();
}
public void setBId(String pBId) {
if (pBId == null) {
b = null;
return;
}
else if (b == null) {
b = new B();
}
this.getB().setId(pBId);
}
public B getB () {
return b;
}
public void setB (pB) {
this.b = pB;
}
}
public class B {
protected String id;
protected String color;
public B () {
}
public B (
String pId, String pColor) {
this.setId(pId);
this.setColor(pColor);
}
public String getId() {
return this.id;
}
public void setId(String pId) {
this.id = pId;
}
public String getColor() {
return this.color;
}
public void setColor(String pColor) {
this.color = pColor;
}
}
If I use
Criteria criteriaA = session.createCriteria( A.class );
Criteria criteriaB = criteriaA.createCriteria( B.class );
criteriaB.addOrder( Order.asc("color") );
criteriaA.list();
Hibernate is using inner join.
So I tried to use
Criteria criteriaA = session.createCriteria( A.class );
criteriaA.setFetchMode(B.class, FetchMode.join);
criteriaA.list();
Now Hibernate uses left join.
But I still have the problem with ordering the result by color.
I tried
Criteria criteriaA = session.createCriteria( A.class );
criteriaA.setFetchMode(B.class, FetchMode.join);
criteriaA.addOrder(Order.asc("b.color"));
criteriaA.list();
and get the error message
org.hibernate.QueryException: could not resolve property: b of: a
Then I tried
Criteria criteriaA = session.createCriteria( A.class );
criteriaA.setFetchMode(B.class, FetchMode.join);
criteriaA.createAlias("B", "b");
criteria.addOrder(Order.asc("b.color"));
criteriaA.list();
but createAlias overwrites the fetchMode and sets it to inner join.
Results with undefined color will disappear.
What should I do ?
Can I use critera in this case or will I have to use HQL ?
|