Hibernate version:3.1.2
Hello,
We have a table PEOPLE with 2 COLUMNS: XNAME, YNAME
XNAME is SET and YNAME is EMPTY
OR
YNAME is SET and XNAME is EMPTY
Forces:
We have to order them by NAME ASC, my idea is to create a specific Projection to do the concatenation, i.e. ORDER BY CONCAT(XNAME,YNAME)
We have to use Criteria API.
So I wrote a specific Projection for this purpose (concatenation).
The question is was there a simpler solution (except creating a view) ???
Code follows:
Code:
public class MyConcatenatorProjection extends SimpleProjection {
private String propertyName;
private String property1;
private String property2;
private boolean grouped;
public MyConcatenatorProjection(String prop) {
this(prop, false);
}
protected MyConcatenatorProjection(String prop, boolean grouped) {
if (prop.split(" ").length != 2)
throw new RuntimeException("Invalid property name: two space-separated properties");
this.property1 = prop.split(" ")[0];
this.property2 = prop.split(" ")[1];
this.grouped = grouped;
}
public String toString() {
return "concat( "+property1+","+property2+")";
}
public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
return new Type[] { Hibernate.STRING };
}
public String toSqlString(Criteria criteria, int position,
CriteriaQuery criteriaQuery) throws HibernateException {
return new StringBuffer().append(
"concat(" + criteriaQuery.getColumn(criteria, property1)+
","+criteriaQuery.getColumn(criteria, property2)+")" )
.append(" as y").append(position).append('_').toString();
}
}