1

我的模型:

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

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

我的元模型:

@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;
    [...]
}

我使用 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean 将 EntityManager 注入我的 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();
    }
}

我可以对我的结果进行排序

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

(按nested.id 排序)

但我想按

ObjectToQuery.Nested.sortBy

我使用 Hibernate 4.2.6.FINAL 作为我的 JPA 实现

4

1 回答 1

2

我自己找到了答案:

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

我希望这可以帮助某人

于 2013-12-13T10:04:40.137 回答