get max value of column using jpa criteria query

Surya picture Surya · Sep 26, 2013 · Viewed 28.1k times · Source

I want to get the maximum value of column relationId from table ElementRelationType I have written code but its giving error

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")));

select and max both giving error how to get the integer max value

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);
}

and

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;
}

Answer

default locale picture default locale · Sep 26, 2013

You didn't post which errors do you receive, so I have to guess.

CriteriaBuilder.max accepts Expression<N> where N extends Number

At the same time Root.get by default returns Path<Object> which is inconvertible to Expression<Number>.

So to make your call to max work you need to specify generic parameter to root.get:

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

here you can replace Number with an actual type of relationId (Long, BigInteger etc.)

UPDATE: @perissf addressed another issue with your code. If you are going to select maximal value (which is numeric) you should declare your CriteriaQuery as a query to Number not ElementRelationTypes