具有ElementCollection的OrderBy的CriteriaQuery

时间:2019-06-12 20:16:06

标签: java hibernate hibernate-criteria

我有一张实体表,我想使用一个属性(即ElementCollection)通过CriteriaQuery.orderBy进行排序。我在Basic(字符串)列上的orderBy没问题。

下面的代码导致:

select certificat0_.Name as Name13_25_, ... from CertificatePolicy certificat0_ cross join CertificatePolicy_Usages usages1_ where certificat0_.dbID=usages1_.CertificatePolicy_id order by . asc offset 0 rows fetch next ? rows only
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'asc'.

在sql中,问题似乎是“ by。asc”,其中“。”应该是“用法”,但以某种方式解析为“。”。不确定为什么冬眠会这样做。

如果我尝试按“名称”列而不是“用法”进行排序,则代码可以正常工作。因此,我显然不够聪明,无法告诉criteriaQuery该怎么做。

这是我的大概代码:

@Entity()
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "ID" }) }, name = "CertificatePolicy")
public class CertificatePolicy {
    @Basic()
    @Column(name = "Name")
    private String name = null;

    @ElementCollection(fetch = FetchType.EAGER)
    @Column(name = "T_element")
    @CollectionTable(joinColumns = { @JoinColumn(name = "CertificatePolicy_id") }, name = "CertificatePolicy_Usages")
    private Set<String> usages = new HashSet<String>();

    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
    @JoinColumns({ @JoinColumn(name = "CertificatePolicy_id") })
    private Set<KeyType> supportedKeyTypes = new HashSet<KeyType>();
}

public List<CertificatePolicy> query() {
    query(0, 10, "name"); // WORKS
    query(0, 10, "usages"); // Fails
    query(0, 10, "supportedKeyTypes"); // Fails
}

private List<CertificatePolicy> fetch(int offset, int limit, String property) {
    EntityManager em = ...;
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<?> criteriaQuery = builder.createQuery(CertificatePolicy.class);
    Root<CertificatePolicy> root = criteriaQuery.from(CertificatePolicy.class);
    List<Order> orders = new ArrayList<>();

    Expression<?> path = root.get(property);
    orders.add( ascending ? builder.asc(path) ? builder.desc(path) );
    criteriaQuery.select(root);
    criteriaQuery.orderBy(orders);
    List<CertificatePolicy> items = em.createQuery(criteriaQuery)
    .setFirstResult(offset).setMaxResults(limit).getResultlList();
    return items;
}

使用休眠5.4.3.Final

0 个答案:

没有答案