编辑:Pascal Thivent在帖子中JPA - Criteria API and EmbeddedId回答
背景:我正在使用具有延迟加载和列排序/过滤的PrimeFaces 5数据表来显示从MySQL数据库中检索的一组数据。
问题:数据集是从包含来自父实体的嵌入式密钥的目标实体中提取的,该实体本身包含来自其父实体的嵌入式密钥(请参阅下面的代码示例)。如何根据其自己的嵌入密钥中的值对目标实体进行排序/过滤?
//
// Top-level entity
//
@Entity
@Table(name = "top_level")
@XmlRootElement
public class TopLevel implements Serializable
{
@Id
@Column(name = "top_level_id")
private Integer topLevelId;
...
}
//
// Primary key of second-level entity
//
@Embeddable
public class SecondLevelPK implements Serializable
{
@Column(name = "top_level_id")
private int topLevelId;
@Column(name = "second_level_name")
private String secondLevelName;
...
}
//
// Second-level entity
//
@Entity
@Table(name = "second_level")
@XmlRootElement
public class SecondLevel implements Serializable
{
@EmbeddedId
protected SecondLevelPK secondLevelPK;
@Column(name = "description")
private String description;
...
}
//
// Primary key of target entity
//
@Embeddable
public class TargetEntityPK implements Serializable
{
@Column(name = "top_level_id")
private int topLevelId;
@Column(name = "second_level_name")
private String secondLevelName;
@Column(name = "target_entity_code")
private String targetCode;
...
}
//
// Target entity
//
@Entity
@Table(name = "target_entity")
@XmlRootElement
public class TargetEntity implements Serializable
{
@EmbeddedId
protected TargetEntityPK targetEntityPK;
@Column(name = "target_entity_title")
private String targetEntityTitle;
...
}
这是成功加载所有记录的条件查询,包括嵌入的键字段: -
CriteriaQuery cq = getCriteriaQuery();
Root<T> rt = cq.from(entityClass); // entityClass type is TargetEntity
cq.select(rt);
Query q = getQuery(cq);
q.getResultList();
我可以对嵌入式密钥不属于的字段进行排序,如下所示: -
cq.orderBy(getCriteriaBuilder().asc(rt.get(sortField)));
我应该如何修改常规查询或orderBy子句以便能够对TargetEntityPK.targetCode
进行排序?
同样我需要能够在同一个字段上进行过滤,但我怀疑排序的答案也会解决过滤问题。