【问题标题】:Hibernate 4 EntityManager CriteriaBuilder sortby nested PropertyHibernate 4 EntityManager CriteriaBuilder sortby嵌套属性
【发布时间】:2013-12-31 05:41:20
【问题描述】:

我的模特:

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

【问题讨论】:

    标签: java spring hibernate jpa hibernate-entitymanager


    【解决方案1】:

    我自己找到了答案:

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

    我希望这对某人有帮助

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 2014-02-07
      • 2016-07-06
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多