Hibernate 4 EntityManager CriteriaBuilder sortby nested Property

1.2k views Asked by At

My model:

public class Nested {
    private Integer id;
    private String sortBy;
    [...]
}

public class ObjectToQuery {
    private Integer id;
    private Nested nested;
    private OtherProperty otherProperty;
    [...]
}

My Metamodel:

@StaticMetamodel(Nested.class)
public class Nested_ {
    public static volatile SingularAttribute<Nested, Integer> id;
    public static volatile SingularAttribute<Nested, String> sortBy;
[...]
}
@StaticMetamodel(ObjectToQuery.class)
public class ObjectToQuery_ {
    public static volatile SingularAttribute<ObjectToQuery, Integer> id;
    public static volatile SingularAttribute<ObjectToQuery, Nested> nested;
    public static volatile SingularAttribute<ObjectToQuery, OtherProperty> otherProperty;
    [...]
}

I use org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean to inject EntityManager into my DAO

public class ObjectToQueryDao {
    @PersistenceContext
    private EntityManager entityManager;

    public List<ObjectToQuery> listObjectToQueryByOtherProperty(OtherProperty otherProperty) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<ObjectToQuery> criteriaQuery = criteriaBuilder
            .createQuery(ObjectToQuery.class);
        Root<ObjectToQuery> rootObjectToQuery = criteriaQuery.from(ObjectToQuery.class);
        criteriaQuery.where(criteriaBuilder.equal(
            rootObjectToQuery.get("otherProperty"), otherProperty));
        return entityManager.createQuery(criteriaQuery).getResultList();
    }
}

I can sort my result with

criteriaQuery.orderBy(criteriaBuilder.asc(rootObjectToQuery
    .get(ObjectToQuery_.nested)));

(which sorts by nested.id)

But I would like to sort by

ObjectToQuery.Nested.sortBy

I use Hibernate 4.2.6.FINAL as my JPA implementation

1

There are 1 answers

0
genericUser On BEST ANSWER

I found the answer myself:

Join<ObjectToQuery, Nested> join = rootObjectToQuery
    .join(ObjectToQuery_.nested);
criteriaQuery.orderBy(criteriaBuilder.asc(join
    .get(Nested_.sortBy)));

I hope this helps somebody