使用jpa条件查询获取列的最大值

时间:2013-09-26 08:04:37

标签: jpa criteria-api

我想从表relationId获取列ElementRelationType的最大值 我编写了代码但是给出了错误

CriteriaBuilder cb1 = entityManager.getCriteriaBuilder();
CriteriaQuery<ElementRelationTypes> cq1 = cb1.createQuery(ElementRelationTypes.class);
Root<ElementRelationTypes> root = cq1.from(ElementRelationTypes.class);
cq1.select(cb1.max(root.get("relationId")));

选择并且最大两者都给出错误 如何获得整数最大值

public class ElementRelationTypes {

private RelationId relationLangPK=new RelationId(); 

private Country country;
private Status status;


@EmbeddedId
public RelationId getRelationLangPK() {
    return relationLangPK;
}
public void setRelationLangPK(RelationId relationLangPK) {
    this.relationLangPK = relationLangPK;
}

@Transient
public Integer getRelationId() {
    return getRelationLangPK().getRelationId();
}
public void setRelationId(Integer relationId) {
    getRelationLangPK().setRelationId(relationId);
}
@Transient
public Language getLanguage() {
    return getRelationLangPK().getLanguage();
}
public void setLanguageCode(Language language) {
    getRelationLangPK().setLanguage(language);
}

public class RelationId implements Serializable {
private static final long serialVersionUID = 1L;
private Integer relationId;
private Language language;

@JoinColumn(name=PersistenseConstants.ELEMENT_RELATION_TYPE_COL_RELATION_ID)
public Integer getRelationId() {
    return relationId;
}

public void setRelationId(Integer relationId) {
    this.relationId = relationId;
}

@OneToOne
@JoinColumn(name=PersistenseConstants.LANGUAGE_ENTITY_COL_LANG_CODE)
public Language getLanguage() {
    return language;
}

public void setLanguage(Language language) {
    this.language = language;
}

1 个答案:

答案 0 :(得分:11)

你没有发布你收到的错误,所以我不得不猜测。

CriteriaBuilder.max接受Expression<N> <{1}}

同时Root.get默认情况下会返回N extends Number Path<Object>无法转换的Expression<Number>

因此,要拨打max工作,您需要为root.get指定通用参数:

cq1.select(cb1.max(root.<Number>get("relationId")));

此处,您可以将Number替换为实际类型relationIdLongBigInteger等。

更新: @perissf addressed您的代码的另一个问题。如果您要选择最大值(数字),则应将CriteriaQuery声明为Number而非ElementRelationTypes

的查询