Hibernate 4 EntityManager CriteriaBuilder sortby嵌套属性

时间:2013-12-12 17:13:07

标签: java spring hibernate jpa hibernate-entitymanager

我的模特:

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实现

1 个答案:

答案 0 :(得分:1)

我自己找到了答案:

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

我希望这有助于某人