我有 2 节课:
@Entity
@Table(name = "DRCOMMENTS" ,schema = "XXX")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Drcomments.findAll", query = "SELECT d FROM Drcomments d"),
public class Drcomments implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected DrcommentsPK drcommentsPK;
@Size(max = 50)
@Column(name = "SDESC")
private String commentSecondaryCodeDescription;
}
@Embeddable
public class DrcommentsPK implements Serializable {
@Column(name = "CODE")
private Short commentPrimaryCode;
@NotNull
@Column(name = "SCODE" , length=5)
private Short commentSecondaryCode;
}
我正在尝试使用动态 order by 和参数创建查询,例如:当 DrcommentsPK.commentPrimaryCode 等于 1 时,我想选择所有 Drcomments 记录,并且 order by 将由 DrcommentsPK.commentSecondaryCode。这是我尝试过的:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Drcomments> q = cb.createQuery(Drcomments.class);
Root<Drcomments> c = q.from(Drcomments.class);
q.select(c);
q.where(cb.equal(c.get("drcommentsPK").get("commentPrimaryCode"), 1));
Path<Drcomments> valuePath = c.get("drcommentsPK").get("commentSecondaryCode");
Order[] orders;
if(sord.equals("desc"))
{
orders = new Order[] {cb.desc(valuePath)};
}
else
{
orders = new Order[] {cb.asc(valuePath)};
}
q.orderBy(orders);
query = em.createQuery(q);
query.setFirstResult(start);
query.setMaxResults(start + limit);
results = query.getResultList();
问题是我得到的结果列表没有按commentSecondaryCode desc顺序排序..
我做错了吗?如何才能做到这一点?如何创建将按可嵌入类中的字段排序的查询?
更新: 这是我得到的生成的 sql:
SELECT * FROM
(SELECT * FROM
(SELECT EL_TEMP.*, ROWNUMBER() OVER() AS EL_ROWNM FROM
(SELECT CMSSDESC AS a1, CMSSCODE AS a4, CMSPCODE AS a5 FROM DRCOMMENTS
WHERE (CMSPCODE = 1) ORDER BY CMSSCODE DESC, CMSPCODE DESC)
AS EL_TEMP)
AS EL_TEMP2 WHERE EL_ROWNM <= 50)
AS EL_TEMP3 WHERE EL_ROWNM > 0
当我运行此代码时,它不会返回 CMSSCODE desc order 中的记录..(因为 order by 应该在外部选择中..)我需要更改query.setFirstResult()
and中的某些内容query.setMaxResults()
吗?我如何将它添加到条件查询的末尾,所以它将在最后一个选择中?
提前致谢。